Нет описания

WebView.android.tsx 7.7KB

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