react-native-webview.git

WebView.ios.tsx 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. */
  8. import React from 'react';
  9. import {
  10. ActivityIndicator,
  11. Text,
  12. UIManager as NotTypedUIManager,
  13. View,
  14. requireNativeComponent,
  15. NativeModules,
  16. Image,
  17. findNodeHandle,
  18. ImageSourcePropType,
  19. } from 'react-native';
  20. import invariant from 'invariant';
  21. import {
  22. defaultOriginWhitelist,
  23. createOnShouldStartLoadWithRequest,
  24. getViewManagerConfig,
  25. } from './WebViewShared';
  26. import {
  27. WebViewErrorEvent,
  28. WebViewMessageEvent,
  29. WebViewNavigationEvent,
  30. WebViewProgressEvent,
  31. IOSWebViewProps,
  32. DecelerationRateConstant,
  33. NativeWebViewIOS,
  34. ViewManager,
  35. State,
  36. CustomUIManager,
  37. } from './WebViewTypes';
  38. import styles from './WebView.styles';
  39. const UIManager = NotTypedUIManager as CustomUIManager;
  40. const resolveAssetSource = Image.resolveAssetSource;
  41. let didWarnAboutUIWebViewUsage = false;
  42. // Imported from https://github.com/facebook/react-native/blob/master/Libraries/Components/ScrollView/processDecelerationRate.js
  43. const processDecelerationRate = (
  44. decelerationRate: DecelerationRateConstant | number | undefined,
  45. ) => {
  46. if (decelerationRate === 'normal') {
  47. decelerationRate = 0.998;
  48. } else if (decelerationRate === 'fast') {
  49. decelerationRate = 0.99;
  50. }
  51. return decelerationRate;
  52. };
  53. const RNCUIWebViewManager = NativeModules.RNCUIWebViewManager as ViewManager;
  54. const RNCWKWebViewManager = NativeModules.RNCWKWebViewManager as ViewManager;
  55. const defaultRenderLoading = () => (
  56. <View style={styles.loadingView}>
  57. <ActivityIndicator />
  58. </View>
  59. );
  60. const defaultRenderError = (
  61. errorDomain: string | undefined,
  62. errorCode: number,
  63. errorDesc: string,
  64. ) => (
  65. <View style={styles.errorContainer}>
  66. <Text style={styles.errorTextTitle}>Error loading page</Text>
  67. <Text style={styles.errorText}>{'Domain: ' + errorDomain}</Text>
  68. <Text style={styles.errorText}>{'Error Code: ' + errorCode}</Text>
  69. <Text style={styles.errorText}>{'Description: ' + errorDesc}</Text>
  70. </View>
  71. );
  72. class WebView extends React.Component<IOSWebViewProps, State> {
  73. static defaultProps = {
  74. useWebKit: true,
  75. cacheEnabled: true,
  76. originWhitelist: defaultOriginWhitelist,
  77. useSharedProcessPool: true,
  78. };
  79. static isFileUploadSupported = async () => {
  80. // no native implementation for iOS, depends only on permissions
  81. return true;
  82. };
  83. state: State = {
  84. viewState: this.props.startInLoadingState ? 'LOADING' : 'IDLE',
  85. lastErrorEvent: null,
  86. };
  87. webViewRef = React.createRef<NativeWebViewIOS>();
  88. UNSAFE_componentWillMount() {
  89. if (!this.props.useWebKit && !didWarnAboutUIWebViewUsage) {
  90. didWarnAboutUIWebViewUsage = true;
  91. console.warn(
  92. 'UIWebView is deprecated and will be removed soon, please use WKWebView (do not override useWebkit={true} prop),' +
  93. ' more infos here: https://github.com/react-native-community/react-native-webview/issues/312',
  94. );
  95. }
  96. if (
  97. this.props.useWebKit === true &&
  98. this.props.scalesPageToFit !== undefined
  99. ) {
  100. console.warn(
  101. 'The scalesPageToFit property is not supported when useWebKit = true',
  102. );
  103. }
  104. if (
  105. !this.props.useWebKit &&
  106. this.props.allowsBackForwardNavigationGestures
  107. ) {
  108. console.warn(
  109. 'The allowsBackForwardNavigationGestures property is not supported when useWebKit = false',
  110. );
  111. }
  112. if (!this.props.useWebKit && this.props.incognito) {
  113. console.warn(
  114. 'The incognito property is not supported when useWebKit = false',
  115. );
  116. }
  117. }
  118. render() {
  119. const {
  120. decelerationRate: decelerationRateProp,
  121. nativeConfig = {},
  122. onMessage,
  123. onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
  124. originWhitelist,
  125. renderError,
  126. renderLoading,
  127. scalesPageToFit = this.props.useWebKit ? undefined : true,
  128. style,
  129. useWebKit,
  130. ...otherProps
  131. } = this.props;
  132. let otherView = null;
  133. if (this.state.viewState === 'LOADING') {
  134. otherView = (renderLoading || defaultRenderLoading)();
  135. } else if (this.state.viewState === 'ERROR') {
  136. const errorEvent = this.state.lastErrorEvent;
  137. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  138. otherView = (renderError || defaultRenderError)(
  139. errorEvent.domain,
  140. errorEvent.code,
  141. errorEvent.description,
  142. );
  143. } else if (this.state.viewState !== 'IDLE') {
  144. console.error(
  145. 'RNCWebView invalid state encountered: ' + this.state.viewState,
  146. );
  147. }
  148. const webViewStyles = [styles.container, styles.webView, style];
  149. if (
  150. this.state.viewState === 'LOADING' ||
  151. this.state.viewState === 'ERROR'
  152. ) {
  153. // if we're in either LOADING or ERROR states, don't show the webView
  154. webViewStyles.push(styles.hidden);
  155. }
  156. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  157. this.onShouldStartLoadWithRequestCallback,
  158. originWhitelist,
  159. onShouldStartLoadWithRequestProp,
  160. );
  161. const decelerationRate = processDecelerationRate(decelerationRateProp);
  162. let NativeWebView = nativeConfig.component as typeof NativeWebViewIOS;
  163. if (useWebKit) {
  164. NativeWebView = NativeWebViewIOS || RNCWKWebView;
  165. } else {
  166. NativeWebView = NativeWebViewIOS || RNCUIWebView;
  167. }
  168. const webView = (
  169. <NativeWebView
  170. {...otherProps}
  171. decelerationRate={decelerationRate}
  172. key="webViewKey"
  173. messagingEnabled={typeof onMessage === 'function'}
  174. onLoadingError={this._onLoadingError}
  175. onLoadingFinish={this._onLoadingFinish}
  176. onLoadingProgress={this._onLoadingProgress}
  177. onLoadingStart={this._onLoadingStart}
  178. onMessage={this._onMessage}
  179. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  180. ref={this.webViewRef}
  181. scalesPageToFit={scalesPageToFit}
  182. // TODO: find a better way to type this.
  183. source={resolveAssetSource(this.props.source as ImageSourcePropType)}
  184. style={webViewStyles}
  185. {...nativeConfig.props}
  186. />
  187. );
  188. return (
  189. <View style={styles.container}>
  190. {webView}
  191. {otherView}
  192. </View>
  193. );
  194. }
  195. _getCommands = () =>
  196. !this.props.useWebKit
  197. ? getViewManagerConfig('RNCUIWebView').Commands
  198. : getViewManagerConfig('RNCWKWebView').Commands;
  199. /**
  200. * Go forward one page in the web view's history.
  201. */
  202. goForward = () => {
  203. UIManager.dispatchViewManagerCommand(
  204. this.getWebViewHandle(),
  205. this._getCommands().goForward,
  206. null,
  207. );
  208. };
  209. /**
  210. * Go back one page in the web view's history.
  211. */
  212. goBack = () => {
  213. UIManager.dispatchViewManagerCommand(
  214. this.getWebViewHandle(),
  215. this._getCommands().goBack,
  216. null,
  217. );
  218. };
  219. /**
  220. * Reloads the current page.
  221. */
  222. reload = () => {
  223. this.setState({ viewState: 'LOADING' });
  224. UIManager.dispatchViewManagerCommand(
  225. this.getWebViewHandle(),
  226. this._getCommands().reload,
  227. null,
  228. );
  229. };
  230. /**
  231. * Stop loading the current page.
  232. */
  233. stopLoading = () => {
  234. UIManager.dispatchViewManagerCommand(
  235. this.getWebViewHandle(),
  236. this._getCommands().stopLoading,
  237. null,
  238. );
  239. };
  240. /**
  241. * Posts a message to the web view, which will emit a `message` event.
  242. * Accepts one argument, `data`, which must be a string.
  243. *
  244. * In your webview, you'll need to something like the following.
  245. *
  246. * ```js
  247. * document.addEventListener('message', e => { document.title = e.data; });
  248. * ```
  249. */
  250. postMessage = (data: string) => {
  251. UIManager.dispatchViewManagerCommand(
  252. this.getWebViewHandle(),
  253. this._getCommands().postMessage,
  254. [String(data)],
  255. );
  256. };
  257. /**
  258. * Injects a javascript string into the referenced WebView. Deliberately does not
  259. * return a response because using eval() to return a response breaks this method
  260. * on pages with a Content Security Policy that disallows eval(). If you need that
  261. * functionality, look into postMessage/onMessage.
  262. */
  263. injectJavaScript = (data: string) => {
  264. UIManager.dispatchViewManagerCommand(
  265. this.getWebViewHandle(),
  266. this._getCommands().injectJavaScript,
  267. [data],
  268. );
  269. };
  270. /**
  271. * We return an event with a bunch of fields including:
  272. * url, title, loading, canGoBack, canGoForward
  273. */
  274. _updateNavigationState = (event: WebViewNavigationEvent) => {
  275. if (this.props.onNavigationStateChange) {
  276. this.props.onNavigationStateChange(event.nativeEvent);
  277. }
  278. };
  279. /**
  280. * Returns the native `WebView` node.
  281. */
  282. getWebViewHandle = () => {
  283. const nodeHandle = findNodeHandle(this.webViewRef.current);
  284. invariant(nodeHandle != null, 'nodeHandle expected to be non-null');
  285. return nodeHandle as number;
  286. };
  287. _onLoadingStart = (event: WebViewNavigationEvent) => {
  288. const onLoadStart = this.props.onLoadStart;
  289. onLoadStart && onLoadStart(event);
  290. this._updateNavigationState(event);
  291. };
  292. _onLoadingError = (event: WebViewErrorEvent) => {
  293. event.persist(); // persist this event because we need to store it
  294. const { onError, onLoadEnd } = this.props;
  295. onError && onError(event);
  296. onLoadEnd && onLoadEnd(event);
  297. console.warn('Encountered an error loading page', event.nativeEvent);
  298. this.setState({
  299. lastErrorEvent: event.nativeEvent,
  300. viewState: 'ERROR',
  301. });
  302. };
  303. _onLoadingFinish = (event: WebViewNavigationEvent) => {
  304. const { onLoad, onLoadEnd } = this.props;
  305. onLoad && onLoad(event);
  306. onLoadEnd && onLoadEnd(event);
  307. this.setState({
  308. viewState: 'IDLE',
  309. });
  310. this._updateNavigationState(event);
  311. };
  312. _onMessage = (event: WebViewMessageEvent) => {
  313. const { onMessage } = this.props;
  314. onMessage && onMessage(event);
  315. };
  316. _onLoadingProgress = (event: WebViewProgressEvent) => {
  317. const { onLoadProgress } = this.props;
  318. onLoadProgress && onLoadProgress(event);
  319. };
  320. onShouldStartLoadWithRequestCallback = (
  321. shouldStart: boolean,
  322. _url: string,
  323. lockIdentifier: number,
  324. ) => {
  325. let viewManager = (this.props.nativeConfig || {}).viewManager;
  326. if (this.props.useWebKit) {
  327. viewManager = viewManager || RNCWKWebViewManager;
  328. } else {
  329. viewManager = viewManager || RNCUIWebViewManager;
  330. }
  331. invariant(viewManager != null, 'viewManager expected to be non-null');
  332. viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
  333. };
  334. componentDidUpdate(prevProps: IOSWebViewProps) {
  335. if (!(prevProps.useWebKit && this.props.useWebKit)) {
  336. return;
  337. }
  338. this._showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
  339. this._showRedboxOnPropChanges(prevProps, 'incognito');
  340. this._showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
  341. this._showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
  342. if (this.props.scalesPageToFit !== undefined) {
  343. console.warn(
  344. 'The scalesPageToFit property is not supported when useWebKit = true',
  345. );
  346. }
  347. }
  348. _showRedboxOnPropChanges(
  349. prevProps: IOSWebViewProps,
  350. propName: keyof IOSWebViewProps,
  351. ) {
  352. if (this.props[propName] !== prevProps[propName]) {
  353. console.error(
  354. `Changes to property ${propName} do nothing after the initial render.`,
  355. );
  356. }
  357. }
  358. }
  359. const RNCUIWebView: typeof NativeWebViewIOS = requireNativeComponent(
  360. 'RNCUIWebView',
  361. );
  362. const RNCWKWebView: typeof NativeWebViewIOS = requireNativeComponent(
  363. 'RNCWKWebView',
  364. );
  365. module.exports = WebView;