react-native-webview.git

WebView.android.js 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. cacheEnabled: 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={
  135. this.props.androidHardwareAccelerationDisabled
  136. }
  137. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  138. domStorageEnabled={this.props.domStorageEnabled}
  139. messagingEnabled={typeof this.props.onMessage === 'function'}
  140. cacheEnabled={this.props.cacheEnabled}
  141. onMessage={this.onMessage}
  142. overScrollMode={this.props.overScrollMode}
  143. contentInset={this.props.contentInset}
  144. automaticallyAdjustContentInsets={
  145. this.props.automaticallyAdjustContentInsets
  146. }
  147. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  148. onContentSizeChange={this.props.onContentSizeChange}
  149. onLoadingStart={this.onLoadingStart}
  150. onLoadingFinish={this.onLoadingFinish}
  151. onLoadingError={this.onLoadingError}
  152. onLoadingProgress={this.onLoadingProgress}
  153. testID={this.props.testID}
  154. geolocationEnabled={this.props.geolocationEnabled}
  155. mediaPlaybackRequiresUserAction={
  156. this.props.mediaPlaybackRequiresUserAction
  157. }
  158. allowUniversalAccessFromFileURLs={
  159. this.props.allowUniversalAccessFromFileURLs
  160. }
  161. mixedContentMode={this.props.mixedContentMode}
  162. saveFormDataDisabled={this.props.saveFormDataDisabled}
  163. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  164. {...nativeConfig.props}
  165. />
  166. );
  167. return (
  168. <View style={styles.container}>
  169. {webView}
  170. {otherView}
  171. </View>
  172. );
  173. }
  174. goForward = () => {
  175. UIManager.dispatchViewManagerCommand(
  176. this.getWebViewHandle(),
  177. UIManager.RNCWebView.Commands.goForward,
  178. null,
  179. );
  180. };
  181. goBack = () => {
  182. UIManager.dispatchViewManagerCommand(
  183. this.getWebViewHandle(),
  184. UIManager.RNCWebView.Commands.goBack,
  185. null,
  186. );
  187. };
  188. reload = () => {
  189. this.setState({
  190. viewState: WebViewState.LOADING,
  191. });
  192. UIManager.dispatchViewManagerCommand(
  193. this.getWebViewHandle(),
  194. UIManager.RNCWebView.Commands.reload,
  195. null,
  196. );
  197. };
  198. stopLoading = () => {
  199. UIManager.dispatchViewManagerCommand(
  200. this.getWebViewHandle(),
  201. UIManager.RNCWebView.Commands.stopLoading,
  202. null,
  203. );
  204. };
  205. postMessage = (data: string) => {
  206. UIManager.dispatchViewManagerCommand(
  207. this.getWebViewHandle(),
  208. UIManager.RNCWebView.Commands.postMessage,
  209. [String(data)],
  210. );
  211. };
  212. /**
  213. * Injects a javascript string into the referenced WebView. Deliberately does not
  214. * return a response because using eval() to return a response breaks this method
  215. * on pages with a Content Security Policy that disallows eval(). If you need that
  216. * functionality, look into postMessage/onMessage.
  217. */
  218. injectJavaScript = (data: string) => {
  219. UIManager.dispatchViewManagerCommand(
  220. this.getWebViewHandle(),
  221. UIManager.RNCWebView.Commands.injectJavaScript,
  222. [data],
  223. );
  224. };
  225. /**
  226. * We return an event with a bunch of fields including:
  227. * url, title, loading, canGoBack, canGoForward
  228. */
  229. updateNavigationState = (event: WebViewNavigationEvent) => {
  230. if (this.props.onNavigationStateChange) {
  231. this.props.onNavigationStateChange(event.nativeEvent);
  232. }
  233. };
  234. getWebViewHandle = () => {
  235. return ReactNative.findNodeHandle(this.webViewRef.current);
  236. };
  237. onLoadingStart = (event: WebViewNavigationEvent) => {
  238. const onLoadStart = this.props.onLoadStart;
  239. onLoadStart && onLoadStart(event);
  240. this.updateNavigationState(event);
  241. };
  242. onLoadingError = (event: WebViewErrorEvent) => {
  243. event.persist(); // persist this event because we need to store it
  244. const { onError, onLoadEnd } = this.props;
  245. onError && onError(event);
  246. onLoadEnd && onLoadEnd(event);
  247. console.warn('Encountered an error loading page', event.nativeEvent);
  248. this.setState({
  249. lastErrorEvent: event.nativeEvent,
  250. viewState: WebViewState.ERROR,
  251. });
  252. };
  253. onLoadingFinish = (event: WebViewNavigationEvent) => {
  254. const { onLoad, onLoadEnd } = this.props;
  255. onLoad && onLoad(event);
  256. onLoadEnd && onLoadEnd(event);
  257. this.setState({
  258. viewState: WebViewState.IDLE,
  259. });
  260. this.updateNavigationState(event);
  261. };
  262. onMessage = (event: WebViewMessageEvent) => {
  263. const { onMessage } = this.props;
  264. onMessage && onMessage(event);
  265. };
  266. onLoadingProgress = (event: WebViewProgressEvent) => {
  267. const { onLoadProgress } = this.props;
  268. onLoadProgress && onLoadProgress(event);
  269. };
  270. onShouldStartLoadWithRequestCallback = (
  271. shouldStart: boolean,
  272. url: string,
  273. ) => {
  274. if (shouldStart) {
  275. UIManager.dispatchViewManagerCommand(
  276. this.getWebViewHandle(),
  277. UIManager.RNCWebView.Commands.loadUrl,
  278. [String(url)],
  279. );
  280. }
  281. };
  282. }
  283. const RNCWebView = requireNativeComponent('RNCWebView');
  284. const styles = StyleSheet.create({
  285. container: {
  286. flex: 1,
  287. },
  288. hidden: {
  289. height: 0,
  290. flex: 0, // disable 'flex:1' when hiding a View
  291. },
  292. loadingView: {
  293. flex: 1,
  294. justifyContent: 'center',
  295. alignItems: 'center',
  296. },
  297. loadingProgressBar: {
  298. height: 20,
  299. },
  300. });
  301. module.exports = WebView;