Bez popisu

WebView.android.tsx 7.8KB

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