react-native-webview.git

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. import React from 'react';
  11. import {
  12. ActivityIndicator,
  13. Linking,
  14. StyleSheet,
  15. Text,
  16. UIManager,
  17. View,
  18. requireNativeComponent,
  19. NativeModules,
  20. Image,
  21. findNodeHandle,
  22. } from 'react-native';
  23. import invariant from 'fbjs/lib/invariant';
  24. import keyMirror from 'fbjs/lib/keyMirror';
  25. import {
  26. defaultOriginWhitelist,
  27. createOnShouldStartLoadWithRequest,
  28. } from './WebViewShared';
  29. import type {
  30. WebViewEvent,
  31. WebViewError,
  32. WebViewErrorEvent,
  33. WebViewMessageEvent,
  34. WebViewNavigationEvent,
  35. WebViewSharedProps,
  36. WebViewSource,
  37. WebViewProgressEvent,
  38. } from './WebViewTypes';
  39. const resolveAssetSource = Image.resolveAssetSource;
  40. // Imported from https://github.com/facebook/react-native/blob/master/Libraries/Components/ScrollView/processDecelerationRate.js
  41. function processDecelerationRate(decelerationRate) {
  42. if (decelerationRate === 'normal') {
  43. decelerationRate = 0.998;
  44. } else if (decelerationRate === 'fast') {
  45. decelerationRate = 0.99;
  46. }
  47. return decelerationRate;
  48. }
  49. const RNCUIWebViewManager = NativeModules.RNCUIWebViewManager;
  50. const RNCWKWebViewManager = NativeModules.RNCWKWebViewManager;
  51. const BGWASH = 'rgba(255,255,255,0.8)';
  52. const WebViewState = keyMirror({
  53. IDLE: null,
  54. LOADING: null,
  55. ERROR: null,
  56. });
  57. const NavigationType = keyMirror({
  58. click: true,
  59. formsubmit: true,
  60. backforward: true,
  61. reload: true,
  62. formresubmit: true,
  63. other: true,
  64. });
  65. const JSNavigationScheme = 'react-js-navigation';
  66. type State = {|
  67. viewState: WebViewState,
  68. lastErrorEvent: ?WebViewError,
  69. |};
  70. const DataDetectorTypes = [
  71. 'phoneNumber',
  72. 'link',
  73. 'address',
  74. 'calendarEvent',
  75. 'trackingNumber',
  76. 'flightNumber',
  77. 'lookupSuggestion',
  78. 'none',
  79. 'all',
  80. ];
  81. const defaultRenderLoading = () => (
  82. <View style={styles.loadingView}>
  83. <ActivityIndicator />
  84. </View>
  85. );
  86. const defaultRenderError = (errorDomain, errorCode, errorDesc) => (
  87. <View style={styles.errorContainer}>
  88. <Text style={styles.errorTextTitle}>Error loading page</Text>
  89. <Text style={styles.errorText}>{'Domain: ' + errorDomain}</Text>
  90. <Text style={styles.errorText}>{'Error Code: ' + errorCode}</Text>
  91. <Text style={styles.errorText}>{'Description: ' + errorDesc}</Text>
  92. </View>
  93. );
  94. /**
  95. * `WebView` renders web content in a native view.
  96. *
  97. *```
  98. * import React, { Component } from 'react';
  99. * import { WebView } from 'react-native';
  100. *
  101. * class MyWeb extends Component {
  102. * render() {
  103. * return (
  104. * <WebView
  105. * source={{uri: 'https://github.com/facebook/react-native'}}
  106. * style={{marginTop: 20}}
  107. * />
  108. * );
  109. * }
  110. * }
  111. *```
  112. *
  113. * You can use this component to navigate back and forth in the web view's
  114. * history and configure various properties for the web content.
  115. */
  116. class WebView extends React.Component<WebViewSharedProps, State> {
  117. static JSNavigationScheme = JSNavigationScheme;
  118. static NavigationType = NavigationType;
  119. static defaultProps = {
  120. useWebKit: true,
  121. cacheEnabled: true,
  122. originWhitelist: defaultOriginWhitelist,
  123. useSharedProcessPool: true,
  124. };
  125. static isFileUploadSupported = async () => {
  126. // no native implementation for iOS, depends only on permissions
  127. return true;
  128. };
  129. state = {
  130. viewState: this.props.startInLoadingState
  131. ? WebViewState.LOADING
  132. : WebViewState.IDLE,
  133. lastErrorEvent: null,
  134. };
  135. webViewRef = React.createRef();
  136. UNSAFE_componentWillMount() {
  137. if (
  138. this.props.useWebKit === true &&
  139. this.props.scalesPageToFit !== undefined
  140. ) {
  141. console.warn(
  142. 'The scalesPageToFit property is not supported when useWebKit = true',
  143. );
  144. }
  145. if (
  146. !this.props.useWebKit &&
  147. this.props.allowsBackForwardNavigationGestures
  148. ) {
  149. console.warn(
  150. 'The allowsBackForwardNavigationGestures property is not supported when useWebKit = false',
  151. );
  152. }
  153. if (!this.props.useWebKit && this.props.incognito) {
  154. console.warn(
  155. 'The incognito property is not supported when useWebKit = false',
  156. );
  157. }
  158. }
  159. render() {
  160. let otherView = null;
  161. let scalesPageToFit;
  162. if (this.props.useWebKit) {
  163. ({ scalesPageToFit } = this.props);
  164. } else {
  165. ({ scalesPageToFit = true } = this.props);
  166. }
  167. if (this.state.viewState === WebViewState.LOADING) {
  168. otherView = (this.props.renderLoading || defaultRenderLoading)();
  169. } else if (this.state.viewState === WebViewState.ERROR) {
  170. const errorEvent = this.state.lastErrorEvent;
  171. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  172. otherView = (this.props.renderError || defaultRenderError)(
  173. errorEvent.domain,
  174. errorEvent.code,
  175. errorEvent.description,
  176. );
  177. } else if (this.state.viewState !== WebViewState.IDLE) {
  178. console.error(
  179. 'RNCWebView invalid state encountered: ' + this.state.viewState,
  180. );
  181. }
  182. const webViewStyles = [styles.container, styles.webView, this.props.style];
  183. if (
  184. this.state.viewState === WebViewState.LOADING ||
  185. this.state.viewState === WebViewState.ERROR
  186. ) {
  187. // if we're in either LOADING or ERROR states, don't show the webView
  188. webViewStyles.push(styles.hidden);
  189. }
  190. const nativeConfig = this.props.nativeConfig || {};
  191. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  192. this.onShouldStartLoadWithRequestCallback,
  193. this.props.originWhitelist,
  194. this.props.onShouldStartLoadWithRequest,
  195. );
  196. const decelerationRate = processDecelerationRate(
  197. this.props.decelerationRate,
  198. );
  199. let source: WebViewSource = this.props.source || {};
  200. if (!this.props.source && this.props.html) {
  201. source = { html: this.props.html };
  202. } else if (!this.props.source && this.props.url) {
  203. source = { uri: this.props.url };
  204. }
  205. let NativeWebView = nativeConfig.component;
  206. if (this.props.useWebKit) {
  207. NativeWebView = NativeWebView || RNCWKWebView;
  208. } else {
  209. NativeWebView = NativeWebView || RNCUIWebView;
  210. }
  211. const webView = (
  212. <NativeWebView
  213. ref={this.webViewRef}
  214. key="webViewKey"
  215. style={webViewStyles}
  216. source={resolveAssetSource(source)}
  217. injectedJavaScript={this.props.injectedJavaScript}
  218. bounces={this.props.bounces}
  219. scrollEnabled={this.props.scrollEnabled}
  220. pagingEnabled={this.props.pagingEnabled}
  221. cacheEnabled={this.props.cacheEnabled}
  222. decelerationRate={decelerationRate}
  223. contentInset={this.props.contentInset}
  224. automaticallyAdjustContentInsets={
  225. this.props.automaticallyAdjustContentInsets
  226. }
  227. hideKeyboardAccessoryView={this.props.hideKeyboardAccessoryView}
  228. allowsBackForwardNavigationGestures={
  229. this.props.allowsBackForwardNavigationGestures
  230. }
  231. incognito={this.props.incognito}
  232. userAgent={this.props.userAgent}
  233. onLoadingStart={this._onLoadingStart}
  234. onLoadingFinish={this._onLoadingFinish}
  235. onLoadingError={this._onLoadingError}
  236. onLoadingProgress={this._onLoadingProgress}
  237. onMessage={this._onMessage}
  238. messagingEnabled={typeof this.props.onMessage === 'function'}
  239. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  240. scalesPageToFit={scalesPageToFit}
  241. allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
  242. mediaPlaybackRequiresUserAction={
  243. this.props.mediaPlaybackRequiresUserAction
  244. }
  245. dataDetectorTypes={this.props.dataDetectorTypes}
  246. useSharedProcessPool={this.props.useSharedProcessPool}
  247. allowsLinkPreview={this.props.allowsLinkPreview}
  248. {...nativeConfig.props}
  249. />
  250. );
  251. return (
  252. <View style={styles.container}>
  253. {webView}
  254. {otherView}
  255. </View>
  256. );
  257. }
  258. _getCommands = () =>
  259. !this.props.useWebKit
  260. ? UIManager.getViewManagerConfig('RNCUIWebView').Commands
  261. : UIManager.getViewManagerConfig('RNCWKWebView').Commands;
  262. /**
  263. * Go forward one page in the web view's history.
  264. */
  265. goForward = () => {
  266. UIManager.dispatchViewManagerCommand(
  267. this.getWebViewHandle(),
  268. this._getCommands().goForward,
  269. null,
  270. );
  271. };
  272. /**
  273. * Go back one page in the web view's history.
  274. */
  275. goBack = () => {
  276. UIManager.dispatchViewManagerCommand(
  277. this.getWebViewHandle(),
  278. this._getCommands().goBack,
  279. null,
  280. );
  281. };
  282. /**
  283. * Reloads the current page.
  284. */
  285. reload = () => {
  286. this.setState({ viewState: WebViewState.LOADING });
  287. UIManager.dispatchViewManagerCommand(
  288. this.getWebViewHandle(),
  289. this._getCommands().reload,
  290. null,
  291. );
  292. };
  293. /**
  294. * Stop loading the current page.
  295. */
  296. stopLoading = () => {
  297. UIManager.dispatchViewManagerCommand(
  298. this.getWebViewHandle(),
  299. this._getCommands().stopLoading,
  300. null,
  301. );
  302. };
  303. /**
  304. * Posts a message to the web view, which will emit a `message` event.
  305. * Accepts one argument, `data`, which must be a string.
  306. *
  307. * In your webview, you'll need to something like the following.
  308. *
  309. * ```js
  310. * document.addEventListener('message', e => { document.title = e.data; });
  311. * ```
  312. */
  313. postMessage = (data: string) => {
  314. UIManager.dispatchViewManagerCommand(
  315. this.getWebViewHandle(),
  316. this._getCommands().postMessage,
  317. [String(data)],
  318. );
  319. };
  320. /**
  321. * Injects a javascript string into the referenced WebView. Deliberately does not
  322. * return a response because using eval() to return a response breaks this method
  323. * on pages with a Content Security Policy that disallows eval(). If you need that
  324. * functionality, look into postMessage/onMessage.
  325. */
  326. injectJavaScript = (data: string) => {
  327. UIManager.dispatchViewManagerCommand(
  328. this.getWebViewHandle(),
  329. this._getCommands().injectJavaScript,
  330. [data],
  331. );
  332. };
  333. /**
  334. * We return an event with a bunch of fields including:
  335. * url, title, loading, canGoBack, canGoForward
  336. */
  337. _updateNavigationState = (event: WebViewNavigationEvent) => {
  338. if (this.props.onNavigationStateChange) {
  339. this.props.onNavigationStateChange(event.nativeEvent);
  340. }
  341. };
  342. /**
  343. * Returns the native `WebView` node.
  344. */
  345. getWebViewHandle = () => {
  346. return findNodeHandle(this.webViewRef.current);
  347. };
  348. _onLoadingStart = (event: WebViewNavigationEvent) => {
  349. const onLoadStart = this.props.onLoadStart;
  350. onLoadStart && onLoadStart(event);
  351. this._updateNavigationState(event);
  352. };
  353. _onLoadingError = (event: WebViewErrorEvent) => {
  354. event.persist(); // persist this event because we need to store it
  355. const { onError, onLoadEnd } = this.props;
  356. onError && onError(event);
  357. onLoadEnd && onLoadEnd(event);
  358. console.warn('Encountered an error loading page', event.nativeEvent);
  359. this.setState({
  360. lastErrorEvent: event.nativeEvent,
  361. viewState: WebViewState.ERROR,
  362. });
  363. };
  364. _onLoadingFinish = (event: WebViewNavigationEvent) => {
  365. const { onLoad, onLoadEnd } = this.props;
  366. onLoad && onLoad(event);
  367. onLoadEnd && onLoadEnd(event);
  368. this.setState({
  369. viewState: WebViewState.IDLE,
  370. });
  371. this._updateNavigationState(event);
  372. };
  373. _onMessage = (event: WebViewMessageEvent) => {
  374. const { onMessage } = this.props;
  375. onMessage && onMessage(event);
  376. };
  377. _onLoadingProgress = (event: WebViewProgressEvent) => {
  378. const { onLoadProgress } = this.props;
  379. onLoadProgress && onLoadProgress(event);
  380. };
  381. onShouldStartLoadWithRequestCallback = (
  382. shouldStart: boolean,
  383. url: string,
  384. lockIdentifier: number,
  385. ) => {
  386. let viewManager = (this.props.nativeConfig || {}).viewManager;
  387. if (this.props.useWebKit) {
  388. viewManager = viewManager || RNCWKWebViewManager;
  389. } else {
  390. viewManager = viewManager || RNCUIWebViewManager;
  391. }
  392. invariant(viewManager != null, 'viewManager expected to be non-null');
  393. viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
  394. };
  395. componentDidUpdate(prevProps: WebViewSharedProps) {
  396. if (!(prevProps.useWebKit && this.props.useWebKit)) {
  397. return;
  398. }
  399. this._showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
  400. this._showRedboxOnPropChanges(prevProps, 'incognito');
  401. this._showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
  402. this._showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
  403. if (this.props.scalesPageToFit !== undefined) {
  404. console.warn(
  405. 'The scalesPageToFit property is not supported when useWebKit = true',
  406. );
  407. }
  408. }
  409. _showRedboxOnPropChanges(prevProps, propName: string) {
  410. if (this.props[propName] !== prevProps[propName]) {
  411. console.error(
  412. `Changes to property ${propName} do nothing after the initial render.`,
  413. );
  414. }
  415. }
  416. }
  417. const RNCUIWebView = requireNativeComponent('RNCUIWebView');
  418. const RNCWKWebView = requireNativeComponent('RNCWKWebView');
  419. const styles = StyleSheet.create({
  420. container: {
  421. flex: 1,
  422. },
  423. errorContainer: {
  424. flex: 1,
  425. justifyContent: 'center',
  426. alignItems: 'center',
  427. backgroundColor: BGWASH,
  428. },
  429. errorText: {
  430. fontSize: 14,
  431. textAlign: 'center',
  432. marginBottom: 2,
  433. },
  434. errorTextTitle: {
  435. fontSize: 15,
  436. fontWeight: '500',
  437. marginBottom: 10,
  438. },
  439. hidden: {
  440. height: 0,
  441. flex: 0, // disable 'flex:1' when hiding a View
  442. },
  443. loadingView: {
  444. backgroundColor: BGWASH,
  445. flex: 1,
  446. justifyContent: 'center',
  447. alignItems: 'center',
  448. height: 100,
  449. },
  450. webView: {
  451. backgroundColor: '#ffffff',
  452. },
  453. });
  454. module.exports = WebView;