react-native-webview.git

WebView.android.js 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. WebViewErrorEvent,
  26. WebViewEvent,
  27. WebViewSharedProps,
  28. WebViewSource,
  29. } from './WebViewTypes';
  30. const resolveAssetSource = Image.resolveAssetSource;
  31. const RCT_WEBVIEW_REF = 'webview';
  32. const WebViewState = keyMirror({
  33. IDLE: null,
  34. LOADING: null,
  35. ERROR: null,
  36. });
  37. const defaultRenderLoading = () => (
  38. <View style={styles.loadingView}>
  39. <ActivityIndicator style={styles.loadingProgressBar} />
  40. </View>
  41. );
  42. type State = {|
  43. viewState: WebViewState,
  44. lastErrorEvent: ?WebViewErrorEvent,
  45. startInLoadingState: boolean,
  46. |};
  47. type WebViewPropsAndroid = $ReadOnly<{|
  48. ...WebViewSharedProps,
  49. onNavigationStateChange?: (event: WebViewEvent) => any,
  50. onContentSizeChange?: (event: WebViewEvent) => any,
  51. /**
  52. * Sets whether Geolocation is enabled. The default is false.
  53. * @platform android
  54. */
  55. geolocationEnabled?: ?boolean,
  56. /**
  57. * Boolean that sets whether JavaScript running in the context of a file
  58. * scheme URL should be allowed to access content from any origin.
  59. * Including accessing content from other file scheme URLs
  60. * @platform android
  61. */
  62. allowUniversalAccessFromFileURLs?: ?boolean,
  63. /**
  64. * Used on Android only, controls whether form autocomplete data should be saved
  65. * @platform android
  66. */
  67. saveFormDataDisabled?: ?boolean,
  68. /*
  69. * Used on Android only, controls whether the given list of URL prefixes should
  70. * make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a
  71. * default activity intent for those URL instead of loading it within the webview.
  72. * Use this to list URLs that WebView cannot handle, e.g. a PDF url.
  73. * @platform android
  74. */
  75. urlPrefixesForDefaultIntent?: $ReadOnlyArray<string>,
  76. |}>;
  77. /**
  78. * Renders a native WebView.
  79. */
  80. class WebView extends React.Component<WebViewPropsAndroid, State> {
  81. static defaultProps = {
  82. javaScriptEnabled: true,
  83. thirdPartyCookiesEnabled: true,
  84. scalesPageToFit: true,
  85. saveFormDataDisabled: false,
  86. originWhitelist: WebViewShared.defaultOriginWhitelist,
  87. };
  88. state = {
  89. viewState: WebViewState.IDLE,
  90. lastErrorEvent: (null: ?WebViewErrorEvent),
  91. startInLoadingState: true,
  92. };
  93. UNSAFE_componentWillMount() {
  94. if (this.props.startInLoadingState) {
  95. this.setState({ viewState: WebViewState.LOADING });
  96. }
  97. }
  98. render() {
  99. let otherView = null;
  100. if (this.state.viewState === WebViewState.LOADING) {
  101. otherView = (this.props.renderLoading || defaultRenderLoading)();
  102. } else if (this.state.viewState === WebViewState.ERROR) {
  103. const errorEvent = this.state.lastErrorEvent;
  104. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  105. otherView =
  106. this.props.renderError &&
  107. this.props.renderError(
  108. errorEvent.domain,
  109. errorEvent.code,
  110. errorEvent.description,
  111. );
  112. } else if (this.state.viewState !== WebViewState.IDLE) {
  113. console.error(
  114. 'RCTWebView invalid state encountered: ' + this.state.viewState,
  115. );
  116. }
  117. const webViewStyles = [styles.container, this.props.style];
  118. if (
  119. this.state.viewState === WebViewState.LOADING ||
  120. this.state.viewState === WebViewState.ERROR
  121. ) {
  122. // if we're in either LOADING or ERROR states, don't show the webView
  123. webViewStyles.push(styles.hidden);
  124. }
  125. let source = this.props.source || ({}: WebViewSource);
  126. if (!this.props.source && this.props.html) {
  127. source = { html: this.props.html };
  128. } else if (!this.props.source && this.props.url) {
  129. source = { uri: this.props.url };
  130. }
  131. if (source.method === 'POST' && source.headers) {
  132. console.warn(
  133. 'WebView: `source.headers` is not supported when using POST.',
  134. );
  135. } else if (source.method === 'GET' && source.body) {
  136. console.warn('WebView: `source.body` is not supported when using GET.');
  137. }
  138. const nativeConfig = this.props.nativeConfig || {};
  139. const originWhitelist = (this.props.originWhitelist || []).map(
  140. WebViewShared.originWhitelistToRegex,
  141. );
  142. let NativeWebView = nativeConfig.component || RCTWebView;
  143. const webView = (
  144. <NativeWebView
  145. ref={RCT_WEBVIEW_REF}
  146. key="webViewKey"
  147. style={webViewStyles}
  148. source={resolveAssetSource(source)}
  149. scalesPageToFit={this.props.scalesPageToFit}
  150. injectedJavaScript={this.props.injectedJavaScript}
  151. userAgent={this.props.userAgent}
  152. javaScriptEnabled={this.props.javaScriptEnabled}
  153. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  154. domStorageEnabled={this.props.domStorageEnabled}
  155. messagingEnabled={typeof this.props.onMessage === 'function'}
  156. onMessage={this.onMessage}
  157. contentInset={this.props.contentInset}
  158. automaticallyAdjustContentInsets={
  159. this.props.automaticallyAdjustContentInsets
  160. }
  161. onContentSizeChange={this.props.onContentSizeChange}
  162. onLoadingStart={this.onLoadingStart}
  163. onLoadingFinish={this.onLoadingFinish}
  164. onLoadingError={this.onLoadingError}
  165. testID={this.props.testID}
  166. geolocationEnabled={this.props.geolocationEnabled}
  167. mediaPlaybackRequiresUserAction={
  168. this.props.mediaPlaybackRequiresUserAction
  169. }
  170. allowUniversalAccessFromFileURLs={
  171. this.props.allowUniversalAccessFromFileURLs
  172. }
  173. originWhitelist={originWhitelist}
  174. mixedContentMode={this.props.mixedContentMode}
  175. saveFormDataDisabled={this.props.saveFormDataDisabled}
  176. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  177. {...nativeConfig.props}
  178. />
  179. );
  180. return (
  181. <View style={styles.container}>
  182. {webView}
  183. {otherView}
  184. </View>
  185. );
  186. }
  187. goForward = () => {
  188. UIManager.dispatchViewManagerCommand(
  189. this.getWebViewHandle(),
  190. UIManager.RCTWebView.Commands.goForward,
  191. null,
  192. );
  193. };
  194. goBack = () => {
  195. UIManager.dispatchViewManagerCommand(
  196. this.getWebViewHandle(),
  197. UIManager.RCTWebView.Commands.goBack,
  198. null,
  199. );
  200. };
  201. reload = () => {
  202. this.setState({
  203. viewState: WebViewState.LOADING,
  204. });
  205. UIManager.dispatchViewManagerCommand(
  206. this.getWebViewHandle(),
  207. UIManager.RCTWebView.Commands.reload,
  208. null,
  209. );
  210. };
  211. stopLoading = () => {
  212. UIManager.dispatchViewManagerCommand(
  213. this.getWebViewHandle(),
  214. UIManager.RCTWebView.Commands.stopLoading,
  215. null,
  216. );
  217. };
  218. postMessage = (data: string) => {
  219. UIManager.dispatchViewManagerCommand(
  220. this.getWebViewHandle(),
  221. UIManager.RCTWebView.Commands.postMessage,
  222. [String(data)],
  223. );
  224. };
  225. /**
  226. * Injects a javascript string into the referenced WebView. Deliberately does not
  227. * return a response because using eval() to return a response breaks this method
  228. * on pages with a Content Security Policy that disallows eval(). If you need that
  229. * functionality, look into postMessage/onMessage.
  230. */
  231. injectJavaScript = (data: string) => {
  232. UIManager.dispatchViewManagerCommand(
  233. this.getWebViewHandle(),
  234. UIManager.RCTWebView.Commands.injectJavaScript,
  235. [data],
  236. );
  237. };
  238. /**
  239. * We return an event with a bunch of fields including:
  240. * url, title, loading, canGoBack, canGoForward
  241. */
  242. updateNavigationState = (event: WebViewEvent) => {
  243. if (this.props.onNavigationStateChange) {
  244. this.props.onNavigationStateChange(event.nativeEvent);
  245. }
  246. };
  247. getWebViewHandle = () => {
  248. return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
  249. };
  250. onLoadingStart = (event: WebViewEvent) => {
  251. const onLoadStart = this.props.onLoadStart;
  252. onLoadStart && onLoadStart(event);
  253. this.updateNavigationState(event);
  254. };
  255. onLoadingError = (event: WebViewEvent) => {
  256. event.persist(); // persist this event because we need to store it
  257. const { onError, onLoadEnd } = this.props;
  258. onError && onError(event);
  259. onLoadEnd && onLoadEnd(event);
  260. console.warn('Encountered an error loading page', event.nativeEvent);
  261. this.setState({
  262. lastErrorEvent: event.nativeEvent,
  263. viewState: WebViewState.ERROR,
  264. });
  265. };
  266. onLoadingFinish = (event: WebViewEvent) => {
  267. const { onLoad, onLoadEnd } = this.props;
  268. onLoad && onLoad(event);
  269. onLoadEnd && onLoadEnd(event);
  270. this.setState({
  271. viewState: WebViewState.IDLE,
  272. });
  273. this.updateNavigationState(event);
  274. };
  275. onMessage = (event: WebViewEvent) => {
  276. const { onMessage } = this.props;
  277. onMessage && onMessage(event);
  278. };
  279. }
  280. const RCTWebView = requireNativeComponent('RCTWebView');
  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;