Nessuna descrizione

WebView.ios.js 13KB

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