Нема описа

WebView.android.tsx 9.4KB

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