No Description

WebView.ios.js 13KB

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