react-native-webview.git

WebView.android.tsx 7.6KB

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