react-native-webview.git

WebView.android.js 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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. */
  9. 'use strict';
  10. import React from 'react';
  11. import PropTypes from 'prop-types';
  12. import ReactNative from 'react-native';
  13. import {
  14. ActivityIndicator,
  15. EdgeInsetsPropType,
  16. StyleSheet,
  17. UIManager,
  18. View,
  19. ViewPropTypes,
  20. Image,
  21. requireNativeComponent
  22. } from 'react-native';
  23. import deprecatedPropType from 'deprecated-prop-type';
  24. import keyMirror from 'fbjs/lib/keyMirror';
  25. import WebViewShared from './WebViewShared';
  26. const resolveAssetSource = Image.resolveAssetSource;
  27. const RNC_WEBVIEW_REF = 'webview';
  28. const WebViewState = keyMirror({
  29. IDLE: null,
  30. LOADING: null,
  31. ERROR: null,
  32. });
  33. const defaultRenderLoading = () => (
  34. <View style={styles.loadingView}>
  35. <ActivityIndicator style={styles.loadingProgressBar} />
  36. </View>
  37. );
  38. /**
  39. * Renders a native WebView.
  40. */
  41. class WebView extends React.Component {
  42. static propTypes = {
  43. ...ViewPropTypes,
  44. renderError: PropTypes.func,
  45. renderLoading: PropTypes.func,
  46. onLoad: PropTypes.func,
  47. onLoadEnd: PropTypes.func,
  48. onLoadStart: PropTypes.func,
  49. onError: PropTypes.func,
  50. automaticallyAdjustContentInsets: PropTypes.bool,
  51. contentInset: EdgeInsetsPropType,
  52. onNavigationStateChange: PropTypes.func,
  53. onMessage: PropTypes.func,
  54. onContentSizeChange: PropTypes.func,
  55. startInLoadingState: PropTypes.bool, // force WebView to show loadingView on first load
  56. style: DeprecatedViewPropTypes.style,
  57. html: deprecatedPropType(
  58. PropTypes.string,
  59. 'Use the `source` prop instead.',
  60. ),
  61. url: deprecatedPropType(PropTypes.string, 'Use the `source` prop instead.'),
  62. /**
  63. * Loads static html or a uri (with optional headers) in the WebView.
  64. */
  65. source: PropTypes.oneOfType([
  66. PropTypes.shape({
  67. /*
  68. * The URI to load in the WebView. Can be a local or remote file.
  69. */
  70. uri: PropTypes.string,
  71. /*
  72. * The HTTP Method to use. Defaults to GET if not specified.
  73. * NOTE: On Android, only GET and POST are supported.
  74. */
  75. method: PropTypes.oneOf(['GET', 'POST']),
  76. /*
  77. * Additional HTTP headers to send with the request.
  78. * NOTE: On Android, this can only be used with GET requests.
  79. */
  80. headers: PropTypes.object,
  81. /*
  82. * The HTTP body to send with the request. This must be a valid
  83. * UTF-8 string, and will be sent exactly as specified, with no
  84. * additional encoding (e.g. URL-escaping or base64) applied.
  85. * NOTE: On Android, this can only be used with POST requests.
  86. */
  87. body: PropTypes.string,
  88. }),
  89. PropTypes.shape({
  90. /*
  91. * A static HTML page to display in the WebView.
  92. */
  93. html: PropTypes.string,
  94. /*
  95. * The base URL to be used for any relative links in the HTML.
  96. */
  97. baseUrl: PropTypes.string,
  98. }),
  99. /*
  100. * Used internally by packager.
  101. */
  102. PropTypes.number,
  103. ]),
  104. /**
  105. * If true, use WKWebView instead of UIWebView.
  106. * @platform ios
  107. */
  108. useWebKit: PropTypes.bool,
  109. /**
  110. * Used on Android only, JS is enabled by default for WebView on iOS
  111. * @platform android
  112. */
  113. javaScriptEnabled: PropTypes.bool,
  114. /**
  115. * Used on Android Lollipop and above only, third party cookies are enabled
  116. * by default for WebView on Android Kitkat and below and on iOS
  117. * @platform android
  118. */
  119. thirdPartyCookiesEnabled: PropTypes.bool,
  120. /**
  121. * Used on Android only, controls whether DOM Storage is enabled or not
  122. * @platform android
  123. */
  124. domStorageEnabled: PropTypes.bool,
  125. /**
  126. * Sets whether Geolocation is enabled. The default is false.
  127. * @platform android
  128. */
  129. geolocationEnabled: PropTypes.bool,
  130. /**
  131. * Sets the JS to be injected when the webpage loads.
  132. */
  133. injectedJavaScript: PropTypes.string,
  134. /**
  135. * Sets whether the webpage scales to fit the view and the user can change the scale.
  136. */
  137. scalesPageToFit: PropTypes.bool,
  138. /**
  139. * Sets the user-agent for this WebView. The user-agent can also be set in native using
  140. * WebViewConfig. This prop will overwrite that config.
  141. */
  142. userAgent: PropTypes.string,
  143. /**
  144. * Used to locate this view in end-to-end tests.
  145. */
  146. testID: PropTypes.string,
  147. /**
  148. * Determines whether HTML5 audio & videos require the user to tap before they can
  149. * start playing. The default value is `false`.
  150. */
  151. mediaPlaybackRequiresUserAction: PropTypes.bool,
  152. /**
  153. * Boolean that sets whether JavaScript running in the context of a file
  154. * scheme URL should be allowed to access content from any origin.
  155. * Including accessing content from other file scheme URLs
  156. * @platform android
  157. */
  158. allowUniversalAccessFromFileURLs: PropTypes.bool,
  159. /**
  160. * List of origin strings to allow being navigated to. The strings allow
  161. * wildcards and get matched against *just* the origin (not the full URL).
  162. * If the user taps to navigate to a new page but the new page is not in
  163. * this whitelist, the URL will be opened by the Android OS.
  164. * The default whitelisted origins are "http://*" and "https://*".
  165. */
  166. originWhitelist: PropTypes.arrayOf(PropTypes.string),
  167. /**
  168. * Function that accepts a string that will be passed to the WebView and
  169. * executed immediately as JavaScript.
  170. */
  171. injectJavaScript: PropTypes.func,
  172. /**
  173. * Specifies the mixed content mode. i.e WebView will allow a secure origin to load content from any other origin.
  174. *
  175. * Possible values for `mixedContentMode` are:
  176. *
  177. * - `'never'` (default) - WebView will not allow a secure origin to load content from an insecure origin.
  178. * - `'always'` - WebView will allow a secure origin to load content from any other origin, even if that origin is insecure.
  179. * - `'compatibility'` - WebView will attempt to be compatible with the approach of a modern web browser with regard to mixed content.
  180. * @platform android
  181. */
  182. mixedContentMode: PropTypes.oneOf(['never', 'always', 'compatibility']),
  183. /**
  184. * Used on Android only, controls whether form autocomplete data should be saved
  185. * @platform android
  186. */
  187. saveFormDataDisabled: PropTypes.bool,
  188. /**
  189. * Override the native component used to render the WebView. Enables a custom native
  190. * WebView which uses the same JavaScript as the original WebView.
  191. */
  192. nativeConfig: PropTypes.shape({
  193. /*
  194. * The native component used to render the WebView.
  195. */
  196. component: PropTypes.any,
  197. /*
  198. * Set props directly on the native component WebView. Enables custom props which the
  199. * original WebView doesn't pass through.
  200. */
  201. props: PropTypes.object,
  202. /*
  203. * Set the ViewManager to use for communication with the native side.
  204. * @platform ios
  205. */
  206. viewManager: PropTypes.object,
  207. }),
  208. /*
  209. * Used on Android only, controls whether the given list of URL prefixes should
  210. * make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a
  211. * default activity intent for those URL instead of loading it within the webview.
  212. * Use this to list URLs that WebView cannot handle, e.g. a PDF url.
  213. * @platform android
  214. */
  215. urlPrefixesForDefaultIntent: PropTypes.arrayOf(PropTypes.string),
  216. };
  217. static defaultProps = {
  218. javaScriptEnabled: true,
  219. thirdPartyCookiesEnabled: true,
  220. scalesPageToFit: true,
  221. saveFormDataDisabled: false,
  222. originWhitelist: WebViewShared.defaultOriginWhitelist,
  223. };
  224. state = {
  225. viewState: WebViewState.IDLE,
  226. lastErrorEvent: null,
  227. startInLoadingState: true,
  228. };
  229. UNSAFE_componentWillMount() {
  230. if (this.props.startInLoadingState) {
  231. this.setState({ viewState: WebViewState.LOADING });
  232. }
  233. }
  234. render() {
  235. let otherView = null;
  236. if (this.state.viewState === WebViewState.LOADING) {
  237. otherView = (this.props.renderLoading || defaultRenderLoading)();
  238. } else if (this.state.viewState === WebViewState.ERROR) {
  239. const errorEvent = this.state.lastErrorEvent;
  240. otherView =
  241. this.props.renderError &&
  242. this.props.renderError(
  243. errorEvent.domain,
  244. errorEvent.code,
  245. errorEvent.description,
  246. );
  247. } else if (this.state.viewState !== WebViewState.IDLE) {
  248. console.error(
  249. 'RCTWebView invalid state encountered: ' + this.state.loading,
  250. );
  251. }
  252. const webViewStyles = [styles.container, this.props.style];
  253. if (
  254. this.state.viewState === WebViewState.LOADING ||
  255. this.state.viewState === WebViewState.ERROR
  256. ) {
  257. // if we're in either LOADING or ERROR states, don't show the webView
  258. webViewStyles.push(styles.hidden);
  259. }
  260. const source = this.props.source || {};
  261. if (this.props.html) {
  262. source.html = this.props.html;
  263. } else if (this.props.url) {
  264. source.uri = this.props.url;
  265. }
  266. if (source.method === 'POST' && source.headers) {
  267. console.warn(
  268. 'WebView: `source.headers` is not supported when using POST.',
  269. );
  270. } else if (source.method === 'GET' && source.body) {
  271. console.warn('WebView: `source.body` is not supported when using GET.');
  272. }
  273. const nativeConfig = this.props.nativeConfig || {};
  274. const originWhitelist = (this.props.originWhitelist || []).map(
  275. WebViewShared.originWhitelistToRegex,
  276. );
  277. let NativeWebView = nativeConfig.component || RCTWebView;
  278. const webView = (
  279. <NativeWebView
  280. ref={RCT_WEBVIEW_REF}
  281. key="webViewKey"
  282. style={webViewStyles}
  283. source={resolveAssetSource(source)}
  284. scalesPageToFit={this.props.scalesPageToFit}
  285. injectedJavaScript={this.props.injectedJavaScript}
  286. userAgent={this.props.userAgent}
  287. javaScriptEnabled={this.props.javaScriptEnabled}
  288. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  289. domStorageEnabled={this.props.domStorageEnabled}
  290. messagingEnabled={typeof this.props.onMessage === 'function'}
  291. onMessage={this.onMessage}
  292. contentInset={this.props.contentInset}
  293. automaticallyAdjustContentInsets={
  294. this.props.automaticallyAdjustContentInsets
  295. }
  296. onContentSizeChange={this.props.onContentSizeChange}
  297. onLoadingStart={this.onLoadingStart}
  298. onLoadingFinish={this.onLoadingFinish}
  299. onLoadingError={this.onLoadingError}
  300. testID={this.props.testID}
  301. geolocationEnabled={this.props.geolocationEnabled}
  302. mediaPlaybackRequiresUserAction={
  303. this.props.mediaPlaybackRequiresUserAction
  304. }
  305. allowUniversalAccessFromFileURLs={
  306. this.props.allowUniversalAccessFromFileURLs
  307. }
  308. originWhitelist={originWhitelist}
  309. mixedContentMode={this.props.mixedContentMode}
  310. saveFormDataDisabled={this.props.saveFormDataDisabled}
  311. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  312. {...nativeConfig.props}
  313. />
  314. );
  315. return (
  316. <View style={styles.container}>
  317. {webView}
  318. {otherView}
  319. </View>
  320. );
  321. }
  322. goForward = () => {
  323. UIManager.dispatchViewManagerCommand(
  324. this.getWebViewHandle(),
  325. UIManager.RCTWebView.Commands.goForward,
  326. null,
  327. );
  328. };
  329. goBack = () => {
  330. UIManager.dispatchViewManagerCommand(
  331. this.getWebViewHandle(),
  332. UIManager.RCTWebView.Commands.goBack,
  333. null,
  334. );
  335. };
  336. reload = () => {
  337. this.setState({
  338. viewState: WebViewState.LOADING,
  339. });
  340. UIManager.dispatchViewManagerCommand(
  341. this.getWebViewHandle(),
  342. UIManager.RCTWebView.Commands.reload,
  343. null,
  344. );
  345. };
  346. stopLoading = () => {
  347. UIManager.dispatchViewManagerCommand(
  348. this.getWebViewHandle(),
  349. UIManager.RCTWebView.Commands.stopLoading,
  350. null,
  351. );
  352. };
  353. postMessage = data => {
  354. UIManager.dispatchViewManagerCommand(
  355. this.getWebViewHandle(),
  356. UIManager.RCTWebView.Commands.postMessage,
  357. [String(data)],
  358. );
  359. };
  360. /**
  361. * Injects a javascript string into the referenced WebView. Deliberately does not
  362. * return a response because using eval() to return a response breaks this method
  363. * on pages with a Content Security Policy that disallows eval(). If you need that
  364. * functionality, look into postMessage/onMessage.
  365. */
  366. injectJavaScript = data => {
  367. UIManager.dispatchViewManagerCommand(
  368. this.getWebViewHandle(),
  369. UIManager.RCTWebView.Commands.injectJavaScript,
  370. [data],
  371. );
  372. };
  373. /**
  374. * We return an event with a bunch of fields including:
  375. * url, title, loading, canGoBack, canGoForward
  376. */
  377. updateNavigationState = event => {
  378. if (this.props.onNavigationStateChange) {
  379. this.props.onNavigationStateChange(event.nativeEvent);
  380. }
  381. };
  382. getWebViewHandle = () => {
  383. return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
  384. };
  385. onLoadingStart = event => {
  386. const onLoadStart = this.props.onLoadStart;
  387. onLoadStart && onLoadStart(event);
  388. this.updateNavigationState(event);
  389. };
  390. onLoadingError = event => {
  391. event.persist(); // persist this event because we need to store it
  392. const { onError, onLoadEnd } = this.props;
  393. onError && onError(event);
  394. onLoadEnd && onLoadEnd(event);
  395. console.warn('Encountered an error loading page', event.nativeEvent);
  396. this.setState({
  397. lastErrorEvent: event.nativeEvent,
  398. viewState: WebViewState.ERROR,
  399. });
  400. };
  401. onLoadingFinish = event => {
  402. const { onLoad, onLoadEnd } = this.props;
  403. onLoad && onLoad(event);
  404. onLoadEnd && onLoadEnd(event);
  405. this.setState({
  406. viewState: WebViewState.IDLE,
  407. });
  408. this.updateNavigationState(event);
  409. };
  410. onMessage = (event) => {
  411. const { onMessage } = this.props;
  412. onMessage && onMessage(event);
  413. };
  414. }
  415. const RCTWebView = requireNativeComponent('RCTWebView');
  416. const styles = StyleSheet.create({
  417. container: {
  418. flex: 1,
  419. },
  420. hidden: {
  421. height: 0,
  422. flex: 0, // disable 'flex:1' when hiding a View
  423. },
  424. loadingView: {
  425. flex: 1,
  426. justifyContent: 'center',
  427. alignItems: 'center',
  428. },
  429. loadingProgressBar: {
  430. height: 20,
  431. },
  432. });
  433. module.exports = WebView;