Aucune description

WebView.android.js 14KB

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