Nessuna descrizione

WebView.android.js 9.5KB

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