react-native-webview.git

WebView.ios.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. * @noflow
  9. */
  10. 'use strict';
  11. import React from 'react';
  12. import ReactNative from 'react-native'
  13. import {
  14. ActivityIndicator,
  15. Linking,
  16. StyleSheet,
  17. Text,
  18. UIManager,
  19. View,
  20. requireNativeComponent,
  21. NativeModules,
  22. Image
  23. } from 'react-native';
  24. import invariant from 'fbjs/lib/invariant';
  25. import keyMirror from 'fbjs/lib/keyMirror';
  26. import WebViewShared from './WebViewShared';
  27. const resolveAssetSource = Image.resolveAssetSource;
  28. // Imported from https://github.com/facebook/react-native/blob/master/Libraries/Components/ScrollView/processDecelerationRate.js
  29. function processDecelerationRate(decelerationRate) {
  30. if (decelerationRate === 'normal') {
  31. decelerationRate = 0.998;
  32. } else if (decelerationRate === 'fast') {
  33. decelerationRate = 0.99;
  34. }
  35. return decelerationRate;
  36. }
  37. const RCTUIWebViewManager = NativeModules.UIWebViewManager;
  38. const RCTWKWebViewManager = NativeModules.WKWebViewManager;
  39. const BGWASH = 'rgba(255,255,255,0.8)';
  40. const RCT_WEBVIEW_REF = 'webview';
  41. const WebViewState = keyMirror({
  42. IDLE: null,
  43. LOADING: null,
  44. ERROR: null,
  45. });
  46. const NavigationType = keyMirror({
  47. click: true,
  48. formsubmit: true,
  49. backforward: true,
  50. reload: true,
  51. formresubmit: true,
  52. other: true,
  53. });
  54. const JSNavigationScheme = 'react-js-navigation';
  55. // type ErrorEvent = {
  56. // domain: any,
  57. // code: any,
  58. // description: any,
  59. // };
  60. // type Event = Object;
  61. const DataDetectorTypes = [
  62. 'phoneNumber',
  63. 'link',
  64. 'address',
  65. 'calendarEvent',
  66. 'trackingNumber',
  67. 'flightNumber',
  68. 'lookupSuggestion',
  69. 'none',
  70. 'all',
  71. ];
  72. const defaultRenderLoading = () => (
  73. <View style={styles.loadingView}>
  74. <ActivityIndicator />
  75. </View>
  76. );
  77. const defaultRenderError = (errorDomain, errorCode, errorDesc) => (
  78. <View style={styles.errorContainer}>
  79. <Text style={styles.errorTextTitle}>Error loading page</Text>
  80. <Text style={styles.errorText}>{'Domain: ' + errorDomain}</Text>
  81. <Text style={styles.errorText}>{'Error Code: ' + errorCode}</Text>
  82. <Text style={styles.errorText}>{'Description: ' + errorDesc}</Text>
  83. </View>
  84. );
  85. /**
  86. * `WebView` renders web content in a native view.
  87. *
  88. *```
  89. * import React, { Component } from 'react';
  90. * import { WebView } from 'react-native';
  91. *
  92. * class MyWeb extends Component {
  93. * render() {
  94. * return (
  95. * <WebView
  96. * source={{uri: 'https://github.com/facebook/react-native'}}
  97. * style={{marginTop: 20}}
  98. * />
  99. * );
  100. * }
  101. * }
  102. *```
  103. *
  104. * You can use this component to navigate back and forth in the web view's
  105. * history and configure various properties for the web content.
  106. */
  107. class WebView extends React.Component {
  108. static JSNavigationScheme = JSNavigationScheme;
  109. static NavigationType = NavigationType;
  110. static defaultProps = {
  111. useWebKit: true,
  112. originWhitelist: WebViewShared.defaultOriginWhitelist,
  113. };
  114. state = {
  115. viewState: WebViewState.IDLE,
  116. lastErrorEvent: null,
  117. startInLoadingState: true,
  118. };
  119. UNSAFE_componentWillMount() {
  120. if (this.props.startInLoadingState) {
  121. this.setState({ viewState: WebViewState.LOADING });
  122. }
  123. if (
  124. this.props.useWebKit === true &&
  125. this.props.scalesPageToFit !== undefined
  126. ) {
  127. console.warn(
  128. 'The scalesPageToFit property is not supported when useWebKit = true',
  129. );
  130. }
  131. }
  132. render() {
  133. let otherView = null;
  134. let scalesPageToFit;
  135. if (this.props.useWebKit) {
  136. ({ scalesPageToFit } = this.props);
  137. } else {
  138. ({ scalesPageToFit = true } = this.props);
  139. }
  140. if (this.state.viewState === WebViewState.LOADING) {
  141. otherView = (this.props.renderLoading || defaultRenderLoading)();
  142. } else if (this.state.viewState === WebViewState.ERROR) {
  143. const errorEvent = this.state.lastErrorEvent;
  144. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  145. otherView = (this.props.renderError || defaultRenderError)(
  146. errorEvent.domain,
  147. errorEvent.code,
  148. errorEvent.description,
  149. );
  150. } else if (this.state.viewState !== WebViewState.IDLE) {
  151. console.error(
  152. 'RCTWebView invalid state encountered: ' + this.state.loading,
  153. );
  154. }
  155. const webViewStyles = [styles.container, styles.webView, this.props.style];
  156. if (
  157. this.state.viewState === WebViewState.LOADING ||
  158. this.state.viewState === WebViewState.ERROR
  159. ) {
  160. // if we're in either LOADING or ERROR states, don't show the webView
  161. webViewStyles.push(styles.hidden);
  162. }
  163. const nativeConfig = this.props.nativeConfig || {};
  164. let viewManager = nativeConfig.viewManager;
  165. if (this.props.useWebKit) {
  166. viewManager = viewManager || RCTWKWebViewManager;
  167. } else {
  168. viewManager = viewManager || RCTUIWebViewManager;
  169. }
  170. const compiledWhitelist = [
  171. 'about:blank',
  172. ...(this.props.originWhitelist || []),
  173. ].map(WebViewShared.originWhitelistToRegex);
  174. const onShouldStartLoadWithRequest = (event) => {
  175. let shouldStart = true;
  176. const { url } = event.nativeEvent;
  177. const origin = WebViewShared.extractOrigin(url);
  178. const passesWhitelist = compiledWhitelist.some(x =>
  179. new RegExp(x).test(origin),
  180. );
  181. shouldStart = shouldStart && passesWhitelist;
  182. if (!passesWhitelist) {
  183. Linking.openURL(url);
  184. }
  185. if (this.props.onShouldStartLoadWithRequest) {
  186. shouldStart =
  187. shouldStart &&
  188. this.props.onShouldStartLoadWithRequest(event.nativeEvent);
  189. }
  190. viewManager.startLoadWithResult(
  191. !!shouldStart,
  192. event.nativeEvent.lockIdentifier,
  193. );
  194. };
  195. const decelerationRate = processDecelerationRate(
  196. this.props.decelerationRate,
  197. );
  198. const source = this.props.source || {};
  199. if (this.props.html) {
  200. source.html = this.props.html;
  201. } else if (this.props.url) {
  202. source.uri = this.props.url;
  203. }
  204. const messagingEnabled = typeof this.props.onMessage === 'function';
  205. let NativeWebView = nativeConfig.component;
  206. if (this.props.useWebKit) {
  207. NativeWebView = NativeWebView || RCTWKWebView;
  208. } else {
  209. NativeWebView = NativeWebView || RCTWebView;
  210. }
  211. const webView = (
  212. <NativeWebView
  213. ref={RCT_WEBVIEW_REF}
  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. decelerationRate={decelerationRate}
  221. contentInset={this.props.contentInset}
  222. automaticallyAdjustContentInsets={
  223. this.props.automaticallyAdjustContentInsets
  224. }
  225. onLoadingStart={this._onLoadingStart}
  226. onLoadingFinish={this._onLoadingFinish}
  227. onLoadingError={this._onLoadingError}
  228. messagingEnabled={messagingEnabled}
  229. onMessage={this._onMessage}
  230. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  231. scalesPageToFit={scalesPageToFit}
  232. allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
  233. mediaPlaybackRequiresUserAction={
  234. this.props.mediaPlaybackRequiresUserAction
  235. }
  236. dataDetectorTypes={this.props.dataDetectorTypes}
  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.RCTWebView.Commands;
  250. }
  251. return UIManager.RCTWKWebView.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 => {
  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 => {
  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) => {
  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 ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
  338. };
  339. _onLoadingStart = (event) => {
  340. const onLoadStart = this.props.onLoadStart;
  341. onLoadStart && onLoadStart(event);
  342. this._updateNavigationState(event);
  343. };
  344. _onLoadingError = (event) => {
  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) => {
  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) => {
  365. const { onMessage } = this.props;
  366. onMessage && onMessage(event);
  367. };
  368. componentDidUpdate(prevProps) {
  369. if (!(prevProps.useWebKit && this.props.useWebKit)) {
  370. return;
  371. }
  372. this._showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
  373. this._showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
  374. this._showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
  375. if (this.props.scalesPageToFit !== undefined) {
  376. console.warn(
  377. 'The scalesPageToFit property is not supported when useWebKit = true',
  378. );
  379. }
  380. }
  381. _showRedboxOnPropChanges(prevProps, propName) {
  382. if (this.props[propName] !== prevProps[propName]) {
  383. console.error(
  384. `Changes to property ${propName} do nothing after the initial render.`,
  385. );
  386. }
  387. }
  388. }
  389. const RCTWebView = requireNativeComponent(
  390. 'RCTWebView',
  391. WebView,
  392. WebView.extraNativeComponentConfig,
  393. );
  394. const RCTWKWebView = requireNativeComponent(
  395. 'RCTWKWebView',
  396. WebView,
  397. WebView.extraNativeComponentConfig,
  398. );
  399. const styles = StyleSheet.create({
  400. container: {
  401. flex: 1,
  402. },
  403. errorContainer: {
  404. flex: 1,
  405. justifyContent: 'center',
  406. alignItems: 'center',
  407. backgroundColor: BGWASH,
  408. },
  409. errorText: {
  410. fontSize: 14,
  411. textAlign: 'center',
  412. marginBottom: 2,
  413. },
  414. errorTextTitle: {
  415. fontSize: 15,
  416. fontWeight: '500',
  417. marginBottom: 10,
  418. },
  419. hidden: {
  420. height: 0,
  421. flex: 0, // disable 'flex:1' when hiding a View
  422. },
  423. loadingView: {
  424. backgroundColor: BGWASH,
  425. flex: 1,
  426. justifyContent: 'center',
  427. alignItems: 'center',
  428. height: 100,
  429. },
  430. webView: {
  431. backgroundColor: '#ffffff',
  432. },
  433. });
  434. module.exports = WebView;