Sin descripción

WebView.ios.js 14KB

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