react-native-webview.git

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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. originWhitelist: defaultOriginWhitelist,
  122. };
  123. static isFileUploadSupported = async () => {
  124. // no native implementation for iOS, depends only on permissions
  125. return true;
  126. }
  127. state = {
  128. viewState: this.props.startInLoadingState
  129. ? WebViewState.LOADING
  130. : WebViewState.IDLE,
  131. lastErrorEvent: null,
  132. };
  133. webViewRef = React.createRef();
  134. UNSAFE_componentWillMount() {
  135. if (
  136. this.props.useWebKit === true &&
  137. this.props.scalesPageToFit !== undefined
  138. ) {
  139. console.warn(
  140. 'The scalesPageToFit property is not supported when useWebKit = true',
  141. );
  142. }
  143. if (
  144. !this.props.useWebKit &&
  145. this.props.allowsBackForwardNavigationGestures
  146. ) {
  147. console.warn(
  148. 'The allowsBackForwardNavigationGestures property is not supported when useWebKit = false',
  149. );
  150. }
  151. }
  152. render() {
  153. let otherView = null;
  154. let scalesPageToFit;
  155. if (this.props.useWebKit) {
  156. ({ scalesPageToFit } = this.props);
  157. } else {
  158. ({ scalesPageToFit = true } = this.props);
  159. }
  160. if (this.state.viewState === WebViewState.LOADING) {
  161. otherView = (this.props.renderLoading || defaultRenderLoading)();
  162. } else if (this.state.viewState === WebViewState.ERROR) {
  163. const errorEvent = this.state.lastErrorEvent;
  164. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  165. otherView = (this.props.renderError || defaultRenderError)(
  166. errorEvent.domain,
  167. errorEvent.code,
  168. errorEvent.description,
  169. );
  170. } else if (this.state.viewState !== WebViewState.IDLE) {
  171. console.error(
  172. 'RNCWebView invalid state encountered: ' + this.state.viewState,
  173. );
  174. }
  175. const webViewStyles = [styles.container, styles.webView, this.props.style];
  176. if (
  177. this.state.viewState === WebViewState.LOADING ||
  178. this.state.viewState === WebViewState.ERROR
  179. ) {
  180. // if we're in either LOADING or ERROR states, don't show the webView
  181. webViewStyles.push(styles.hidden);
  182. }
  183. const nativeConfig = this.props.nativeConfig || {};
  184. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  185. this.onShouldStartLoadWithRequestCallback,
  186. this.props.originWhitelist,
  187. this.props.onShouldStartLoadWithRequest,
  188. );
  189. const decelerationRate = processDecelerationRate(
  190. this.props.decelerationRate,
  191. );
  192. let source: WebViewSource = this.props.source || {};
  193. if (!this.props.source && this.props.html) {
  194. source = { html: this.props.html };
  195. } else if (!this.props.source && this.props.url) {
  196. source = { uri: this.props.url };
  197. }
  198. const messagingEnabled = typeof this.props.onMessage === 'function';
  199. let NativeWebView = nativeConfig.component;
  200. if (this.props.useWebKit) {
  201. NativeWebView = NativeWebView || RNCWKWebView;
  202. } else {
  203. NativeWebView = NativeWebView || RNCUIWebView;
  204. }
  205. const webView = (
  206. <NativeWebView
  207. ref={this.webViewRef}
  208. key="webViewKey"
  209. style={webViewStyles}
  210. source={resolveAssetSource(source)}
  211. injectedJavaScript={this.props.injectedJavaScript}
  212. bounces={this.props.bounces}
  213. scrollEnabled={this.props.scrollEnabled}
  214. pagingEnabled={this.props.pagingEnabled}
  215. decelerationRate={decelerationRate}
  216. contentInset={this.props.contentInset}
  217. automaticallyAdjustContentInsets={
  218. this.props.automaticallyAdjustContentInsets
  219. }
  220. hideKeyboardAccessoryView={this.props.hideKeyboardAccessoryView}
  221. allowsBackForwardNavigationGestures={this.props.allowsBackForwardNavigationGestures}
  222. userAgent={this.props.userAgent}
  223. onLoadingStart={this._onLoadingStart}
  224. onLoadingFinish={this._onLoadingFinish}
  225. onLoadingError={this._onLoadingError}
  226. onLoadingProgress={this._onLoadingProgress}
  227. messagingEnabled={messagingEnabled}
  228. onMessage={this._onMessage}
  229. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  230. scalesPageToFit={scalesPageToFit}
  231. allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
  232. mediaPlaybackRequiresUserAction={
  233. this.props.mediaPlaybackRequiresUserAction
  234. }
  235. dataDetectorTypes={this.props.dataDetectorTypes}
  236. allowsLinkPreview={this.props.allowsLinkPreview}
  237. {...nativeConfig.props}
  238. />
  239. );
  240. return (
  241. <View style={styles.container}>
  242. {webView}
  243. {otherView}
  244. </View>
  245. );
  246. }
  247. _getCommands() {
  248. if (!this.props.useWebKit) {
  249. return UIManager.RNCUIWebView.Commands;
  250. }
  251. return UIManager.RNCWKWebView.Commands;
  252. }
  253. /**
  254. * Go forward one page in the web view's history.
  255. */
  256. goForward = () => {
  257. UIManager.dispatchViewManagerCommand(
  258. this.getWebViewHandle(),
  259. this._getCommands().goForward,
  260. null,
  261. );
  262. };
  263. /**
  264. * Go back one page in the web view's history.
  265. */
  266. goBack = () => {
  267. UIManager.dispatchViewManagerCommand(
  268. this.getWebViewHandle(),
  269. this._getCommands().goBack,
  270. null,
  271. );
  272. };
  273. /**
  274. * Reloads the current page.
  275. */
  276. reload = () => {
  277. this.setState({ viewState: WebViewState.LOADING });
  278. UIManager.dispatchViewManagerCommand(
  279. this.getWebViewHandle(),
  280. this._getCommands().reload,
  281. null,
  282. );
  283. };
  284. /**
  285. * Stop loading the current page.
  286. */
  287. stopLoading = () => {
  288. UIManager.dispatchViewManagerCommand(
  289. this.getWebViewHandle(),
  290. this._getCommands().stopLoading,
  291. null,
  292. );
  293. };
  294. /**
  295. * Posts a message to the web view, which will emit a `message` event.
  296. * Accepts one argument, `data`, which must be a string.
  297. *
  298. * In your webview, you'll need to something like the following.
  299. *
  300. * ```js
  301. * document.addEventListener('message', e => { document.title = e.data; });
  302. * ```
  303. */
  304. postMessage = (data: string) => {
  305. UIManager.dispatchViewManagerCommand(
  306. this.getWebViewHandle(),
  307. this._getCommands().postMessage,
  308. [String(data)],
  309. );
  310. };
  311. /**
  312. * Injects a javascript string into the referenced WebView. Deliberately does not
  313. * return a response because using eval() to return a response breaks this method
  314. * on pages with a Content Security Policy that disallows eval(). If you need that
  315. * functionality, look into postMessage/onMessage.
  316. */
  317. injectJavaScript = (data: string) => {
  318. UIManager.dispatchViewManagerCommand(
  319. this.getWebViewHandle(),
  320. this._getCommands().injectJavaScript,
  321. [data],
  322. );
  323. };
  324. /**
  325. * We return an event with a bunch of fields including:
  326. * url, title, loading, canGoBack, canGoForward
  327. */
  328. _updateNavigationState = (event: WebViewNavigationEvent) => {
  329. if (this.props.onNavigationStateChange) {
  330. this.props.onNavigationStateChange(event.nativeEvent);
  331. }
  332. };
  333. /**
  334. * Returns the native `WebView` node.
  335. */
  336. getWebViewHandle = () => {
  337. return findNodeHandle(this.webViewRef.current);
  338. };
  339. _onLoadingStart = (event: WebViewNavigationEvent) => {
  340. const onLoadStart = this.props.onLoadStart;
  341. onLoadStart && onLoadStart(event);
  342. this._updateNavigationState(event);
  343. };
  344. _onLoadingError = (event: WebViewErrorEvent) => {
  345. event.persist(); // persist this event because we need to store it
  346. const { onError, onLoadEnd } = this.props;
  347. onError && onError(event);
  348. onLoadEnd && onLoadEnd(event);
  349. console.warn('Encountered an error loading page', event.nativeEvent);
  350. this.setState({
  351. lastErrorEvent: event.nativeEvent,
  352. viewState: WebViewState.ERROR,
  353. });
  354. };
  355. _onLoadingFinish = (event: WebViewNavigationEvent) => {
  356. const { onLoad, onLoadEnd } = this.props;
  357. onLoad && onLoad(event);
  358. onLoadEnd && onLoadEnd(event);
  359. this.setState({
  360. viewState: WebViewState.IDLE,
  361. });
  362. this._updateNavigationState(event);
  363. };
  364. _onMessage = (event: WebViewMessageEvent) => {
  365. const { onMessage } = this.props;
  366. onMessage && onMessage(event);
  367. };
  368. _onLoadingProgress = (event: WebViewProgressEvent) => {
  369. const { onLoadProgress } = this.props;
  370. onLoadProgress && onLoadProgress(event);
  371. };
  372. onShouldStartLoadWithRequestCallback = (
  373. shouldStart: boolean,
  374. url: string,
  375. lockIdentifier: number,
  376. ) => {
  377. let viewManager = (this.props.nativeConfig || {}).viewManager;
  378. if (this.props.useWebKit) {
  379. viewManager = viewManager || RNCWKWebViewManager;
  380. } else {
  381. viewManager = viewManager || RNCUIWebViewManager;
  382. }
  383. invariant(viewManager != null, 'viewManager expected to be non-null');
  384. viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
  385. };
  386. componentDidUpdate(prevProps: WebViewSharedProps) {
  387. if (!(prevProps.useWebKit && this.props.useWebKit)) {
  388. return;
  389. }
  390. this._showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
  391. this._showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
  392. this._showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
  393. if (this.props.scalesPageToFit !== undefined) {
  394. console.warn(
  395. 'The scalesPageToFit property is not supported when useWebKit = true',
  396. );
  397. }
  398. }
  399. _showRedboxOnPropChanges(prevProps, propName: string) {
  400. if (this.props[propName] !== prevProps[propName]) {
  401. console.error(
  402. `Changes to property ${propName} do nothing after the initial render.`,
  403. );
  404. }
  405. }
  406. }
  407. const RNCUIWebView = requireNativeComponent('RNCUIWebView');
  408. const RNCWKWebView = requireNativeComponent('RNCWKWebView');
  409. const styles = StyleSheet.create({
  410. container: {
  411. flex: 1,
  412. },
  413. errorContainer: {
  414. flex: 1,
  415. justifyContent: 'center',
  416. alignItems: 'center',
  417. backgroundColor: BGWASH,
  418. },
  419. errorText: {
  420. fontSize: 14,
  421. textAlign: 'center',
  422. marginBottom: 2,
  423. },
  424. errorTextTitle: {
  425. fontSize: 15,
  426. fontWeight: '500',
  427. marginBottom: 10,
  428. },
  429. hidden: {
  430. height: 0,
  431. flex: 0, // disable 'flex:1' when hiding a View
  432. },
  433. loadingView: {
  434. backgroundColor: BGWASH,
  435. flex: 1,
  436. justifyContent: 'center',
  437. alignItems: 'center',
  438. height: 100,
  439. },
  440. webView: {
  441. backgroundColor: '#ffffff',
  442. },
  443. });
  444. module.exports = WebView;