react-native-webview.git

WebView.ios.js 13KB

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