Няма описание

WebView.android.tsx 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. const WebViewState: {
  43. IDLE: 'IDLE';
  44. LOADING: 'LOADING';
  45. ERROR: 'ERROR';
  46. } = {
  47. IDLE: 'IDLE',
  48. LOADING: 'LOADING',
  49. ERROR: 'ERROR',
  50. };
  51. const isWebViewUriSource = (
  52. source: WebViewSource,
  53. ): source is WebViewSourceUri =>
  54. typeof source !== 'number' && !('html' in source);
  55. const defaultRenderLoading = (): React.ReactNode => (
  56. <View style={styles.loadingView}>
  57. <ActivityIndicator style={styles.loadingProgressBar} />
  58. </View>
  59. );
  60. type State = {
  61. viewState: 'IDLE' | 'LOADING' | 'ERROR';
  62. lastErrorEvent: WebViewError | null;
  63. };
  64. const RNCWebView = requireNativeComponent('RNCWebView');
  65. /**
  66. * Renders a native WebView.
  67. */
  68. export default class WebView extends React.Component<
  69. WebViewSharedProps,
  70. State
  71. > {
  72. static defaultProps = {
  73. overScrollMode: 'always',
  74. javaScriptEnabled: true,
  75. thirdPartyCookiesEnabled: true,
  76. scalesPageToFit: true,
  77. allowFileAccess: false,
  78. saveFormDataDisabled: false,
  79. originWhitelist: WebViewShared.defaultOriginWhitelist,
  80. };
  81. static isFileUploadSupported = async (): Promise<boolean> =>
  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 = (): void => {
  92. UIManager.dispatchViewManagerCommand(
  93. this.getWebViewHandle(),
  94. UIManager.RNCWebView.Commands.goForward,
  95. null,
  96. );
  97. };
  98. goBack = (): void => {
  99. UIManager.dispatchViewManagerCommand(
  100. this.getWebViewHandle(),
  101. UIManager.RNCWebView.Commands.goBack,
  102. null,
  103. );
  104. };
  105. reload = (): void => {
  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 = (): void => {
  116. UIManager.dispatchViewManagerCommand(
  117. this.getWebViewHandle(),
  118. UIManager.RNCWebView.Commands.stopLoading,
  119. null,
  120. );
  121. };
  122. postMessage = (data: string): void => {
  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): void => {
  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): void => {
  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): void => {
  154. const { onLoadStart } = this.props;
  155. if (onLoadStart) {
  156. onLoadStart(event);
  157. }
  158. this.updateNavigationState(event);
  159. };
  160. onLoadingError = (event: WebViewErrorEvent): void => {
  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): void => {
  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): void => {
  190. const { onMessage } = this.props;
  191. if (onMessage) {
  192. onMessage(event);
  193. }
  194. };
  195. onLoadingProgress = (
  196. event: NativeSyntheticEvent<WebViewProgressEvent>,
  197. ): void => {
  198. const { onLoadProgress } = this.props;
  199. if (onLoadProgress) {
  200. onLoadProgress(event);
  201. }
  202. };
  203. render(): React.ReactNode {
  204. let otherView = null;
  205. if (this.state.viewState === WebViewState.LOADING) {
  206. otherView = (this.props.renderLoading || defaultRenderLoading)();
  207. } else if (this.state.viewState === WebViewState.ERROR) {
  208. const errorEvent = this.state.lastErrorEvent;
  209. if (errorEvent) {
  210. otherView
  211. = this.props.renderError
  212. && this.props.renderError(
  213. errorEvent.domain,
  214. errorEvent.code,
  215. errorEvent.description,
  216. );
  217. } else {
  218. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  219. }
  220. } else if (this.state.viewState !== WebViewState.IDLE) {
  221. // eslint-disable-next-line no-console
  222. console.error(
  223. `RNCWebView invalid state encountered: ${this.state.viewState}`,
  224. );
  225. }
  226. const webViewStyles = [styles.container, this.props.style];
  227. if (
  228. this.state.viewState === WebViewState.LOADING
  229. || this.state.viewState === WebViewState.ERROR
  230. ) {
  231. // if we're in either LOADING or ERROR states, don't show the webView
  232. webViewStyles.push(styles.hidden);
  233. }
  234. let source: WebViewSource = this.props.source || {};
  235. if (!this.props.source && this.props.html) {
  236. source = { html: this.props.html };
  237. } else if (!this.props.source && this.props.url) {
  238. source = { uri: this.props.url };
  239. }
  240. if (isWebViewUriSource(source)) {
  241. if (source.method === 'POST' && source.headers) {
  242. // eslint-disable-next-line no-console
  243. console.warn(
  244. 'WebView: `source.headers` is not supported when using POST.',
  245. );
  246. } else if (source.method === 'GET' && source.body) {
  247. // eslint-disable-next-line no-console
  248. console.warn('WebView: `source.body` is not supported when using GET.');
  249. }
  250. }
  251. const nativeConfig = this.props.nativeConfig || {};
  252. const originWhitelist = (this.props.originWhitelist || []).map(
  253. WebViewShared.originWhitelistToRegex,
  254. );
  255. const NativeWebView = nativeConfig.component || RNCWebView;
  256. const webView = (
  257. <NativeWebView
  258. ref={this.webViewRef}
  259. key="webViewKey"
  260. style={webViewStyles}
  261. source={Image.resolveAssetSource(source as WebViewSourceUri)} // typing issue of not compatible of WebViewSourceHtml in react native.
  262. scalesPageToFit={this.props.scalesPageToFit}
  263. allowFileAccess={this.props.allowFileAccess}
  264. injectedJavaScript={this.props.injectedJavaScript}
  265. userAgent={this.props.userAgent}
  266. javaScriptEnabled={this.props.javaScriptEnabled}
  267. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  268. domStorageEnabled={this.props.domStorageEnabled}
  269. messagingEnabled={typeof this.props.onMessage === 'function'}
  270. onMessage={this.onMessage}
  271. overScrollMode={this.props.overScrollMode}
  272. contentInset={this.props.contentInset}
  273. automaticallyAdjustContentInsets={
  274. this.props.automaticallyAdjustContentInsets
  275. }
  276. onContentSizeChange={this.props.onContentSizeChange}
  277. onLoadingStart={this.onLoadingStart}
  278. onLoadingFinish={this.onLoadingFinish}
  279. onLoadingError={this.onLoadingError}
  280. onLoadingProgress={this.onLoadingProgress}
  281. testID={this.props.testID}
  282. geolocationEnabled={this.props.geolocationEnabled}
  283. mediaPlaybackRequiresUserAction={
  284. this.props.mediaPlaybackRequiresUserAction
  285. }
  286. allowUniversalAccessFromFileURLs={
  287. this.props.allowUniversalAccessFromFileURLs
  288. }
  289. originWhitelist={originWhitelist}
  290. mixedContentMode={this.props.mixedContentMode}
  291. saveFormDataDisabled={this.props.saveFormDataDisabled}
  292. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  293. {...nativeConfig.props}
  294. />
  295. );
  296. return (
  297. <View style={styles.container}>
  298. {webView}
  299. {otherView}
  300. </View>
  301. );
  302. }
  303. }