react-native-webview.git

WebView.ios.js 14KB

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