No Description

WebView.android.tsx 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import React from 'react';
  2. import {
  3. Image,
  4. requireNativeComponent,
  5. UIManager as NotTypedUIManager,
  6. View,
  7. NativeModules,
  8. ImageSourcePropType,
  9. findNodeHandle,
  10. } from 'react-native';
  11. import BatchedBridge from 'react-native/Libraries/BatchedBridge/BatchedBridge';
  12. import invariant from 'invariant';
  13. import {
  14. defaultOriginWhitelist,
  15. createOnShouldStartLoadWithRequest,
  16. defaultRenderError,
  17. defaultRenderLoading,
  18. } from './WebViewShared';
  19. import {
  20. WebViewRenderProcessGoneEvent,
  21. WebViewErrorEvent,
  22. WebViewHttpErrorEvent,
  23. WebViewMessageEvent,
  24. WebViewNavigationEvent,
  25. WebViewProgressEvent,
  26. AndroidWebViewProps,
  27. NativeWebViewAndroid,
  28. State,
  29. RNCWebViewUIManagerAndroid,
  30. } from './WebViewTypes';
  31. import styles from './WebView.styles';
  32. const UIManager = NotTypedUIManager as RNCWebViewUIManagerAndroid;
  33. const RNCWebView = requireNativeComponent(
  34. 'RNCWebView',
  35. ) as typeof NativeWebViewAndroid;
  36. const { resolveAssetSource } = Image;
  37. /**
  38. * A simple counter to uniquely identify WebView instances. Do not use this for anything else.
  39. */
  40. let uniqueRef = 0;
  41. /**
  42. * Renders a native WebView.
  43. */
  44. class WebView extends React.Component<AndroidWebViewProps, State> {
  45. static defaultProps = {
  46. overScrollMode: 'always',
  47. javaScriptEnabled: true,
  48. thirdPartyCookiesEnabled: true,
  49. scalesPageToFit: true,
  50. allowsFullscreenVideo: false,
  51. allowFileAccess: false,
  52. saveFormDataDisabled: false,
  53. cacheEnabled: true,
  54. androidHardwareAccelerationDisabled: false,
  55. androidLayerType: 'none',
  56. originWhitelist: defaultOriginWhitelist,
  57. };
  58. static isFileUploadSupported = async () => {
  59. // native implementation should return "true" only for Android 5+
  60. return NativeModules.RNCWebView.isFileUploadSupported();
  61. };
  62. startUrl: string | null = null;
  63. state: State = {
  64. viewState: this.props.startInLoadingState ? 'LOADING' : 'IDLE',
  65. lastErrorEvent: null,
  66. };
  67. webViewRef = React.createRef<NativeWebViewAndroid>();
  68. messagingModuleName = `WebViewMessageHandler${uniqueRef+=1}`;
  69. componentDidMount = () => {
  70. BatchedBridge.registerCallableModule(this.messagingModuleName, this);
  71. };
  72. getCommands = () => UIManager.getViewManagerConfig('RNCWebView').Commands;
  73. goForward = () => {
  74. UIManager.dispatchViewManagerCommand(
  75. this.getWebViewHandle(),
  76. this.getCommands().goForward,
  77. undefined
  78. );
  79. };
  80. goBack = () => {
  81. UIManager.dispatchViewManagerCommand(
  82. this.getWebViewHandle(),
  83. this.getCommands().goBack,
  84. undefined
  85. );
  86. };
  87. reload = () => {
  88. this.setState({
  89. viewState: 'LOADING',
  90. });
  91. UIManager.dispatchViewManagerCommand(
  92. this.getWebViewHandle(),
  93. this.getCommands().reload,
  94. undefined
  95. );
  96. };
  97. stopLoading = () => {
  98. UIManager.dispatchViewManagerCommand(
  99. this.getWebViewHandle(),
  100. this.getCommands().stopLoading,
  101. undefined
  102. );
  103. };
  104. requestFocus = () => {
  105. UIManager.dispatchViewManagerCommand(
  106. this.getWebViewHandle(),
  107. this.getCommands().requestFocus,
  108. undefined
  109. );
  110. };
  111. postMessage = (data: string) => {
  112. UIManager.dispatchViewManagerCommand(
  113. this.getWebViewHandle(),
  114. this.getCommands().postMessage,
  115. [String(data)],
  116. );
  117. };
  118. clearFormData = () => {
  119. UIManager.dispatchViewManagerCommand(
  120. this.getWebViewHandle(),
  121. this.getCommands().clearFormData,
  122. undefined,
  123. );
  124. }
  125. clearCache = (includeDiskFiles: boolean) => {
  126. UIManager.dispatchViewManagerCommand(
  127. this.getWebViewHandle(),
  128. this.getCommands().clearCache,
  129. [includeDiskFiles],
  130. );
  131. };
  132. clearHistory = () => {
  133. UIManager.dispatchViewManagerCommand(
  134. this.getWebViewHandle(),
  135. this.getCommands().clearHistory,
  136. undefined,
  137. );
  138. };
  139. /**
  140. * Injects a javascript string into the referenced WebView. Deliberately does not
  141. * return a response because using eval() to return a response breaks this method
  142. * on pages with a Content Security Policy that disallows eval(). If you need that
  143. * functionality, look into postMessage/onMessage.
  144. */
  145. injectJavaScript = (data: string) => {
  146. UIManager.dispatchViewManagerCommand(
  147. this.getWebViewHandle(),
  148. this.getCommands().injectJavaScript,
  149. [data],
  150. );
  151. };
  152. /**
  153. * We return an event with a bunch of fields including:
  154. * url, title, loading, canGoBack, canGoForward
  155. */
  156. updateNavigationState = (event: WebViewNavigationEvent) => {
  157. if (this.props.onNavigationStateChange) {
  158. this.props.onNavigationStateChange(event.nativeEvent);
  159. }
  160. };
  161. /**
  162. * Returns the native `WebView` node.
  163. */
  164. getWebViewHandle = () => {
  165. const nodeHandle = findNodeHandle(this.webViewRef.current);
  166. invariant(nodeHandle != null, 'nodeHandle expected to be non-null');
  167. return nodeHandle as number;
  168. };
  169. onLoadingStart = (event: WebViewNavigationEvent) => {
  170. const { onLoadStart } = this.props;
  171. const { nativeEvent: { url } } = event;
  172. this.startUrl = url;
  173. if (onLoadStart) {
  174. onLoadStart(event);
  175. }
  176. this.updateNavigationState(event);
  177. };
  178. onLoadingError = (event: WebViewErrorEvent) => {
  179. event.persist(); // persist this event because we need to store it
  180. const { onError, onLoadEnd } = this.props;
  181. if (onError) {
  182. onError(event);
  183. }
  184. if (onLoadEnd) {
  185. onLoadEnd(event);
  186. }
  187. console.warn('Encountered an error loading page', event.nativeEvent);
  188. this.setState({
  189. lastErrorEvent: event.nativeEvent,
  190. viewState: 'ERROR',
  191. });
  192. };
  193. onHttpError = (event: WebViewHttpErrorEvent) => {
  194. const { onHttpError } = this.props;
  195. if (onHttpError) {
  196. onHttpError(event);
  197. }
  198. }
  199. onRenderProcessGone = (event: WebViewRenderProcessGoneEvent) => {
  200. const { onRenderProcessGone } = this.props;
  201. if (onRenderProcessGone) {
  202. onRenderProcessGone(event);
  203. }
  204. }
  205. onLoadingFinish = (event: WebViewNavigationEvent) => {
  206. const { onLoad, onLoadEnd } = this.props;
  207. const { nativeEvent: { url } } = event;
  208. if (onLoad) {
  209. onLoad(event);
  210. }
  211. if (onLoadEnd) {
  212. onLoadEnd(event);
  213. }
  214. if (url === this.startUrl) {
  215. this.setState({
  216. viewState: 'IDLE',
  217. });
  218. }
  219. this.updateNavigationState(event);
  220. };
  221. onMessage = (event: WebViewMessageEvent) => {
  222. const { onMessage } = this.props;
  223. if (onMessage) {
  224. onMessage(event);
  225. }
  226. };
  227. onLoadingProgress = (event: WebViewProgressEvent) => {
  228. const { onLoadProgress } = this.props;
  229. const { nativeEvent: { progress } } = event;
  230. if (progress === 1) {
  231. this.setState((state) => {
  232. if (state.viewState === 'LOADING') {
  233. return { viewState: 'IDLE' };
  234. }
  235. return null;
  236. });
  237. }
  238. if (onLoadProgress) {
  239. onLoadProgress(event);
  240. }
  241. };
  242. onShouldStartLoadWithRequestCallback = (
  243. shouldStart: boolean,
  244. url: string,
  245. ) => {
  246. if (shouldStart) {
  247. UIManager.dispatchViewManagerCommand(
  248. this.getWebViewHandle(),
  249. this.getCommands().loadUrl,
  250. [String(url)],
  251. );
  252. }
  253. };
  254. render() {
  255. const {
  256. onMessage,
  257. onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
  258. originWhitelist,
  259. renderError,
  260. renderLoading,
  261. source,
  262. style,
  263. containerStyle,
  264. nativeConfig = {},
  265. ...otherProps
  266. } = this.props;
  267. let otherView = null;
  268. if (this.state.viewState === 'LOADING') {
  269. otherView = (renderLoading || defaultRenderLoading)();
  270. } else if (this.state.viewState === 'ERROR') {
  271. const errorEvent = this.state.lastErrorEvent;
  272. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  273. otherView = (renderError || defaultRenderError)(
  274. errorEvent.domain,
  275. errorEvent.code,
  276. errorEvent.description,
  277. );
  278. } else if (this.state.viewState !== 'IDLE') {
  279. console.error(
  280. `RNCWebView invalid state encountered: ${this.state.viewState}`,
  281. );
  282. }
  283. const webViewStyles = [styles.container, styles.webView, style];
  284. const webViewContainerStyle = [styles.container, containerStyle];
  285. if (typeof source !== "number" && source && 'method' in source) {
  286. if (source.method === 'POST' && source.headers) {
  287. console.warn(
  288. 'WebView: `source.headers` is not supported when using POST.',
  289. );
  290. } else if (source.method === 'GET' && source.body) {
  291. console.warn('WebView: `source.body` is not supported when using GET.');
  292. }
  293. }
  294. const NativeWebView
  295. = (nativeConfig.component as typeof NativeWebViewAndroid) || RNCWebView;
  296. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  297. this.onShouldStartLoadWithRequestCallback,
  298. // casting cause it's in the default props
  299. originWhitelist as readonly string[],
  300. onShouldStartLoadWithRequestProp,
  301. );
  302. const webView = (
  303. <NativeWebView
  304. key="webViewKey"
  305. {...otherProps}
  306. messagingEnabled={typeof onMessage === 'function'}
  307. messagingModuleName={this.messagingModuleName}
  308. onLoadingError={this.onLoadingError}
  309. onLoadingFinish={this.onLoadingFinish}
  310. onLoadingProgress={this.onLoadingProgress}
  311. onLoadingStart={this.onLoadingStart}
  312. onHttpError={this.onHttpError}
  313. onRenderProcessGone={this.onRenderProcessGone}
  314. onMessage={this.onMessage}
  315. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  316. ref={this.webViewRef}
  317. // TODO: find a better way to type this.
  318. source={resolveAssetSource(source as ImageSourcePropType)}
  319. style={webViewStyles}
  320. {...nativeConfig.props}
  321. />
  322. );
  323. return (
  324. <View style={webViewContainerStyle}>
  325. {webView}
  326. {otherView}
  327. </View>
  328. );
  329. }
  330. }
  331. export default WebView;