No Description

WebView.ios.js 13KB

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