Ei kuvausta

WebView.android.tsx 7.9KB

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