暫無描述

WebView.ios.tsx 12KB

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