No Description

WebView.android.tsx 9.4KB

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