react-native-webview.git

WebView.android.tsx 7.6KB

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