react-native-webview.git

WebView.android.js 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. import React from 'react';
  12. import ReactNative from 'react-native';
  13. import {
  14. ActivityIndicator,
  15. StyleSheet,
  16. UIManager,
  17. View,
  18. Image,
  19. requireNativeComponent
  20. } from 'react-native';
  21. import invariant from 'fbjs/lib/invariant';
  22. import keyMirror from 'fbjs/lib/keyMirror';
  23. import WebViewShared from './WebViewShared';
  24. import type {
  25. WebViewEvent,
  26. WebViewError,
  27. WebViewErrorEvent,
  28. WebViewMessageEvent,
  29. WebViewNavigation,
  30. WebViewNavigationEvent,
  31. WebViewSharedProps,
  32. WebViewSource,
  33. WebViewProgressEvent,
  34. } from './WebViewTypes';
  35. const resolveAssetSource = Image.resolveAssetSource;
  36. const WebViewState = keyMirror({
  37. IDLE: null,
  38. LOADING: null,
  39. ERROR: null,
  40. });
  41. const defaultRenderLoading = () => (
  42. <View style={styles.loadingView}>
  43. <ActivityIndicator style={styles.loadingProgressBar} />
  44. </View>
  45. );
  46. type State = {|
  47. viewState: WebViewState,
  48. lastErrorEvent: ?WebViewError,
  49. |};
  50. /**
  51. * Renders a native WebView.
  52. */
  53. class WebView extends React.Component<WebViewSharedProps, State> {
  54. static defaultProps = {
  55. overScrollMode: 'always',
  56. javaScriptEnabled: true,
  57. thirdPartyCookiesEnabled: true,
  58. scalesPageToFit: true,
  59. allowFileAccess: false,
  60. saveFormDataDisabled: false,
  61. originWhitelist: WebViewShared.defaultOriginWhitelist,
  62. enableCache: true,
  63. };
  64. state = {
  65. viewState: this.props.startInLoadingState ? WebViewState.LOADING : WebViewState.IDLE,
  66. lastErrorEvent: null,
  67. };
  68. webViewRef = React.createRef();
  69. render() {
  70. let otherView = null;
  71. if (this.state.viewState === WebViewState.LOADING) {
  72. otherView = (this.props.renderLoading || defaultRenderLoading)();
  73. } else if (this.state.viewState === WebViewState.ERROR) {
  74. const errorEvent = this.state.lastErrorEvent;
  75. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  76. otherView =
  77. this.props.renderError &&
  78. this.props.renderError(
  79. errorEvent.domain,
  80. errorEvent.code,
  81. errorEvent.description,
  82. );
  83. } else if (this.state.viewState !== WebViewState.IDLE) {
  84. console.error(
  85. 'RNCWebView invalid state encountered: ' + this.state.viewState,
  86. );
  87. }
  88. const webViewStyles = [styles.container, this.props.style];
  89. if (
  90. this.state.viewState === WebViewState.LOADING ||
  91. this.state.viewState === WebViewState.ERROR
  92. ) {
  93. // if we're in either LOADING or ERROR states, don't show the webView
  94. webViewStyles.push(styles.hidden);
  95. }
  96. let source: WebViewSource = this.props.source || {};
  97. if (!this.props.source && this.props.html) {
  98. source = { html: this.props.html };
  99. } else if (!this.props.source && this.props.url) {
  100. source = { uri: this.props.url };
  101. }
  102. if (source.method === 'POST' && source.headers) {
  103. console.warn(
  104. 'WebView: `source.headers` is not supported when using POST.',
  105. );
  106. } else if (source.method === 'GET' && source.body) {
  107. console.warn('WebView: `source.body` is not supported when using GET.');
  108. }
  109. const nativeConfig = this.props.nativeConfig || {};
  110. const originWhitelist = (this.props.originWhitelist || []).map(
  111. WebViewShared.originWhitelistToRegex,
  112. );
  113. let NativeWebView = nativeConfig.component || RNCWebView;
  114. const webView = (
  115. <NativeWebView
  116. ref={this.webViewRef}
  117. key="webViewKey"
  118. style={webViewStyles}
  119. source={resolveAssetSource(source)}
  120. scalesPageToFit={this.props.scalesPageToFit}
  121. allowFileAccess={this.props.allowFileAccess}
  122. injectedJavaScript={this.props.injectedJavaScript}
  123. userAgent={this.props.userAgent}
  124. javaScriptEnabled={this.props.javaScriptEnabled}
  125. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  126. domStorageEnabled={this.props.domStorageEnabled}
  127. messagingEnabled={typeof this.props.onMessage === 'function'}
  128. onMessage={this.onMessage}
  129. overScrollMode={this.props.overScrollMode}
  130. contentInset={this.props.contentInset}
  131. automaticallyAdjustContentInsets={
  132. this.props.automaticallyAdjustContentInsets
  133. }
  134. onContentSizeChange={this.props.onContentSizeChange}
  135. onLoadingStart={this.onLoadingStart}
  136. onLoadingFinish={this.onLoadingFinish}
  137. onLoadingError={this.onLoadingError}
  138. onLoadingProgress={this.onLoadingProgress}
  139. testID={this.props.testID}
  140. geolocationEnabled={this.props.geolocationEnabled}
  141. mediaPlaybackRequiresUserAction={
  142. this.props.mediaPlaybackRequiresUserAction
  143. }
  144. allowUniversalAccessFromFileURLs={
  145. this.props.allowUniversalAccessFromFileURLs
  146. }
  147. originWhitelist={originWhitelist}
  148. mixedContentMode={this.props.mixedContentMode}
  149. saveFormDataDisabled={this.props.saveFormDataDisabled}
  150. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  151. {...nativeConfig.props}
  152. />
  153. );
  154. return (
  155. <View style={styles.container}>
  156. {webView}
  157. {otherView}
  158. </View>
  159. );
  160. }
  161. goForward = () => {
  162. UIManager.dispatchViewManagerCommand(
  163. this.getWebViewHandle(),
  164. UIManager.RNCWebView.Commands.goForward,
  165. null,
  166. );
  167. };
  168. goBack = () => {
  169. UIManager.dispatchViewManagerCommand(
  170. this.getWebViewHandle(),
  171. UIManager.RNCWebView.Commands.goBack,
  172. null,
  173. );
  174. };
  175. reload = () => {
  176. this.setState({
  177. viewState: WebViewState.LOADING,
  178. });
  179. UIManager.dispatchViewManagerCommand(
  180. this.getWebViewHandle(),
  181. UIManager.RNCWebView.Commands.reload,
  182. null,
  183. );
  184. };
  185. stopLoading = () => {
  186. UIManager.dispatchViewManagerCommand(
  187. this.getWebViewHandle(),
  188. UIManager.RNCWebView.Commands.stopLoading,
  189. null,
  190. );
  191. };
  192. postMessage = (data: string) => {
  193. UIManager.dispatchViewManagerCommand(
  194. this.getWebViewHandle(),
  195. UIManager.RNCWebView.Commands.postMessage,
  196. [String(data)],
  197. );
  198. };
  199. /**
  200. * Injects a javascript string into the referenced WebView. Deliberately does not
  201. * return a response because using eval() to return a response breaks this method
  202. * on pages with a Content Security Policy that disallows eval(). If you need that
  203. * functionality, look into postMessage/onMessage.
  204. */
  205. injectJavaScript = (data: string) => {
  206. UIManager.dispatchViewManagerCommand(
  207. this.getWebViewHandle(),
  208. UIManager.RNCWebView.Commands.injectJavaScript,
  209. [data],
  210. );
  211. };
  212. /**
  213. * We return an event with a bunch of fields including:
  214. * url, title, loading, canGoBack, canGoForward
  215. */
  216. updateNavigationState = (event: WebViewNavigationEvent) => {
  217. if (this.props.onNavigationStateChange) {
  218. this.props.onNavigationStateChange(event.nativeEvent);
  219. }
  220. };
  221. getWebViewHandle = () => {
  222. return ReactNative.findNodeHandle(this.webViewRef.current);
  223. };
  224. onLoadingStart = (event: WebViewNavigationEvent) => {
  225. const onLoadStart = this.props.onLoadStart;
  226. onLoadStart && onLoadStart(event);
  227. this.updateNavigationState(event);
  228. };
  229. onLoadingError = (event: WebViewErrorEvent) => {
  230. event.persist(); // persist this event because we need to store it
  231. const { onError, onLoadEnd } = this.props;
  232. onError && onError(event);
  233. onLoadEnd && onLoadEnd(event);
  234. console.warn('Encountered an error loading page', event.nativeEvent);
  235. this.setState({
  236. lastErrorEvent: event.nativeEvent,
  237. viewState: WebViewState.ERROR,
  238. });
  239. };
  240. onLoadingFinish = (event: WebViewNavigationEvent) => {
  241. const { onLoad, onLoadEnd } = this.props;
  242. onLoad && onLoad(event);
  243. onLoadEnd && onLoadEnd(event);
  244. this.setState({
  245. viewState: WebViewState.IDLE,
  246. });
  247. this.updateNavigationState(event);
  248. };
  249. onMessage = (event: WebViewMessageEvent) => {
  250. const { onMessage } = this.props;
  251. onMessage && onMessage(event);
  252. };
  253. onLoadingProgress = (event: WebViewProgressEvent) => {
  254. const { onLoadProgress} = this.props;
  255. onLoadProgress && onLoadProgress(event);
  256. }
  257. }
  258. const RNCWebView = requireNativeComponent('RNCWebView');
  259. const styles = StyleSheet.create({
  260. container: {
  261. flex: 1,
  262. },
  263. hidden: {
  264. height: 0,
  265. flex: 0, // disable 'flex:1' when hiding a View
  266. },
  267. loadingView: {
  268. flex: 1,
  269. justifyContent: 'center',
  270. alignItems: 'center',
  271. },
  272. loadingProgressBar: {
  273. height: 20,
  274. },
  275. });
  276. module.exports = WebView;