Bez popisu

WebView.android.tsx 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. defaultRenderError,
  16. defaultRenderLoading,
  17. } from './WebViewShared';
  18. import {
  19. WebViewErrorEvent,
  20. WebViewHttpErrorEvent,
  21. WebViewMessageEvent,
  22. WebViewNavigationEvent,
  23. WebViewProgressEvent,
  24. AndroidWebViewProps,
  25. NativeWebViewAndroid,
  26. State,
  27. RNCWebViewUIManager,
  28. } from './WebViewTypes';
  29. import styles from './WebView.styles';
  30. const UIManager = NotTypedUIManager as RNCWebViewUIManager;
  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. allowsFullscreenVideo: false,
  45. allowFileAccess: false,
  46. saveFormDataDisabled: false,
  47. cacheEnabled: true,
  48. androidHardwareAccelerationDisabled: false,
  49. originWhitelist: defaultOriginWhitelist,
  50. };
  51. static isFileUploadSupported = async () => {
  52. // native implementation should return "true" only for Android 5+
  53. return NativeModules.RNCWebView.isFileUploadSupported();
  54. };
  55. startUrl: string | null = null;
  56. state: State = {
  57. viewState: this.props.startInLoadingState ? 'LOADING' : 'IDLE',
  58. lastErrorEvent: null,
  59. };
  60. webViewRef = React.createRef<NativeWebViewAndroid>();
  61. getCommands = () => UIManager.getViewManagerConfig('RNCWebView').Commands;
  62. goForward = () => {
  63. UIManager.dispatchViewManagerCommand(
  64. this.getWebViewHandle(),
  65. this.getCommands().goForward,
  66. undefined
  67. );
  68. };
  69. goBack = () => {
  70. UIManager.dispatchViewManagerCommand(
  71. this.getWebViewHandle(),
  72. this.getCommands().goBack,
  73. undefined
  74. );
  75. };
  76. reload = () => {
  77. this.setState({
  78. viewState: 'LOADING',
  79. });
  80. UIManager.dispatchViewManagerCommand(
  81. this.getWebViewHandle(),
  82. this.getCommands().reload,
  83. undefined
  84. );
  85. };
  86. stopLoading = () => {
  87. UIManager.dispatchViewManagerCommand(
  88. this.getWebViewHandle(),
  89. this.getCommands().stopLoading,
  90. undefined
  91. );
  92. };
  93. requestFocus = () => {
  94. UIManager.dispatchViewManagerCommand(
  95. this.getWebViewHandle(),
  96. this.getCommands().requestFocus,
  97. undefined
  98. );
  99. };
  100. postMessage = (data: string) => {
  101. UIManager.dispatchViewManagerCommand(
  102. this.getWebViewHandle(),
  103. this.getCommands().postMessage,
  104. [String(data)],
  105. );
  106. };
  107. /**
  108. * Injects a javascript string into the referenced WebView. Deliberately does not
  109. * return a response because using eval() to return a response breaks this method
  110. * on pages with a Content Security Policy that disallows eval(). If you need that
  111. * functionality, look into postMessage/onMessage.
  112. */
  113. injectJavaScript = (data: string) => {
  114. UIManager.dispatchViewManagerCommand(
  115. this.getWebViewHandle(),
  116. this.getCommands().injectJavaScript,
  117. [data],
  118. );
  119. };
  120. /**
  121. * We return an event with a bunch of fields including:
  122. * url, title, loading, canGoBack, canGoForward
  123. */
  124. updateNavigationState = (event: WebViewNavigationEvent) => {
  125. if (this.props.onNavigationStateChange) {
  126. this.props.onNavigationStateChange(event.nativeEvent);
  127. }
  128. };
  129. /**
  130. * Returns the native `WebView` node.
  131. */
  132. getWebViewHandle = () => {
  133. const nodeHandle = findNodeHandle(this.webViewRef.current);
  134. invariant(nodeHandle != null, 'nodeHandle expected to be non-null');
  135. return nodeHandle as number;
  136. };
  137. onLoadingStart = (event: WebViewNavigationEvent) => {
  138. const { onLoadStart } = this.props;
  139. const { nativeEvent: { url } } = event;
  140. this.startUrl = url;
  141. if (onLoadStart) {
  142. onLoadStart(event);
  143. }
  144. this.updateNavigationState(event);
  145. };
  146. onLoadingError = (event: WebViewErrorEvent) => {
  147. event.persist(); // persist this event because we need to store it
  148. const { onError, onLoadEnd } = this.props;
  149. if (onError) {
  150. onError(event);
  151. }
  152. if (onLoadEnd) {
  153. onLoadEnd(event);
  154. }
  155. console.warn('Encountered an error loading page', event.nativeEvent);
  156. this.setState({
  157. lastErrorEvent: event.nativeEvent,
  158. viewState: 'ERROR',
  159. });
  160. };
  161. onHttpError = (event: WebViewHttpErrorEvent) => {
  162. const { onHttpError } = this.props;
  163. if (onHttpError) {
  164. onHttpError(event);
  165. }
  166. }
  167. onLoadingFinish = (event: WebViewNavigationEvent) => {
  168. const { onLoad, onLoadEnd } = this.props;
  169. const { nativeEvent: { url } } = event;
  170. if (onLoad) {
  171. onLoad(event);
  172. }
  173. if (onLoadEnd) {
  174. onLoadEnd(event);
  175. }
  176. if (url === this.startUrl) {
  177. this.setState({
  178. viewState: 'IDLE',
  179. });
  180. }
  181. this.updateNavigationState(event);
  182. };
  183. onMessage = (event: WebViewMessageEvent) => {
  184. const { onMessage } = this.props;
  185. if (onMessage) {
  186. onMessage(event);
  187. }
  188. };
  189. onLoadingProgress = (event: WebViewProgressEvent) => {
  190. const { onLoadProgress } = this.props;
  191. const { nativeEvent: { progress } } = event;
  192. if (progress === 1) {
  193. this.setState({
  194. viewState: 'IDLE',
  195. });
  196. }
  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. this.getCommands().loadUrl,
  209. [String(url)],
  210. );
  211. }
  212. };
  213. render() {
  214. const {
  215. onMessage,
  216. onShouldStartLoadWithRequest: onShouldStartLoadWithRequestProp,
  217. originWhitelist,
  218. renderError,
  219. renderLoading,
  220. source,
  221. style,
  222. nativeConfig = {},
  223. ...otherProps
  224. } = this.props;
  225. let otherView = null;
  226. if (this.state.viewState === 'LOADING') {
  227. otherView = (renderLoading || defaultRenderLoading)();
  228. } else if (this.state.viewState === 'ERROR') {
  229. const errorEvent = this.state.lastErrorEvent;
  230. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  231. otherView = (renderError || defaultRenderError)(
  232. errorEvent.domain,
  233. errorEvent.code,
  234. errorEvent.description,
  235. );
  236. } else if (this.state.viewState !== 'IDLE') {
  237. console.error(
  238. `RNCWebView invalid state encountered: ${this.state.viewState}`,
  239. );
  240. }
  241. const webViewStyles = [styles.container, styles.webView, style];
  242. if (source && 'method' in source) {
  243. if (source.method === 'POST' && source.headers) {
  244. console.warn(
  245. 'WebView: `source.headers` is not supported when using POST.',
  246. );
  247. } else if (source.method === 'GET' && source.body) {
  248. console.warn('WebView: `source.body` is not supported when using GET.');
  249. }
  250. }
  251. const NativeWebView
  252. = (nativeConfig.component as typeof NativeWebViewAndroid) || RNCWebView;
  253. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  254. this.onShouldStartLoadWithRequestCallback,
  255. // casting cause it's in the default props
  256. originWhitelist as readonly string[],
  257. onShouldStartLoadWithRequestProp,
  258. );
  259. const webView = (
  260. <NativeWebView
  261. key="webViewKey"
  262. {...otherProps}
  263. messagingEnabled={typeof onMessage === 'function'}
  264. onLoadingError={this.onLoadingError}
  265. onLoadingFinish={this.onLoadingFinish}
  266. onLoadingProgress={this.onLoadingProgress}
  267. onLoadingStart={this.onLoadingStart}
  268. onHttpError={this.onHttpError}
  269. onMessage={this.onMessage}
  270. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  271. ref={this.webViewRef}
  272. // TODO: find a better way to type this.
  273. source={resolveAssetSource(source as ImageSourcePropType)}
  274. style={webViewStyles}
  275. {...nativeConfig.props}
  276. />
  277. );
  278. return (
  279. <View style={styles.container}>
  280. {webView}
  281. {otherView}
  282. </View>
  283. );
  284. }
  285. }
  286. export default WebView;