react-native-webview.git

WebView.ios.js 13KB

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