react-native-webview.git

WebView.android.tsx 9.0KB

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