react-native-webview.git

WebView.android.js 9.2KB

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