Geen omschrijving

WebView.ios.js 14KB

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