react-native-webview.git

WebView.ios.tsx 11KB

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