Bez popisu

WebView.android.tsx 9.0KB

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