暫無描述

WebView.ios.js 12KB

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