No Description

WebView.ios.tsx 10KB

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