react-native-webview.git

WebView.android.js 14KB

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