react-native-webview.git

WebView.ios.tsx 8.9KB

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