Няма описание

WebView.android.tsx 9.4KB

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