react-native-webview.git

WebView.android.tsx 8.6KB

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