No Description

WebView.ios.js 13KB

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