No Description

WebView.android.tsx 7.7KB

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