Няма описание

WebView.android.js 14KB

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