Nenhuma descrição

WebView.android.js 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. 'use strict';
  11. import React from 'react';
  12. import ReactNative from 'react-native';
  13. import {
  14. ActivityIndicator,
  15. StyleSheet,
  16. UIManager,
  17. View,
  18. Image,
  19. requireNativeComponent
  20. } from 'react-native';
  21. import invariant from 'fbjs/lib/invariant';
  22. import keyMirror from 'fbjs/lib/keyMirror';
  23. import WebViewShared from './WebViewShared';
  24. import type {
  25. WebViewEvent,
  26. WebViewError,
  27. WebViewErrorEvent,
  28. WebViewMessageEvent,
  29. WebViewNavigation,
  30. WebViewNavigationEvent,
  31. WebViewSharedProps,
  32. WebViewSource,
  33. } from './WebViewTypes';
  34. const resolveAssetSource = Image.resolveAssetSource;
  35. const RCT_WEBVIEW_REF = 'webview';
  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. startInLoadingState: boolean,
  50. |};
  51. type WebViewPropsAndroid = $ReadOnly<{|
  52. ...WebViewSharedProps,
  53. onNavigationStateChange?: (event: WebViewNavigation) => mixed,
  54. onContentSizeChange?: (event: WebViewEvent) => mixed,
  55. /**
  56. * Sets whether Geolocation is enabled. The default is false.
  57. * @platform android
  58. */
  59. geolocationEnabled?: ?boolean,
  60. /**
  61. * Boolean that sets whether JavaScript running in the context of a file
  62. * scheme URL should be allowed to access content from any origin.
  63. * Including accessing content from other file scheme URLs
  64. * @platform android
  65. */
  66. allowUniversalAccessFromFileURLs?: ?boolean,
  67. /**
  68. * Used on Android only, controls whether form autocomplete data should be saved
  69. * @platform android
  70. */
  71. saveFormDataDisabled?: ?boolean,
  72. /*
  73. * Used on Android only, controls whether the given list of URL prefixes should
  74. * make {@link com.facebook.react.views.webview.ReactWebViewClient} to launch a
  75. * default activity intent for those URL instead of loading it within the webview.
  76. * Use this to list URLs that WebView cannot handle, e.g. a PDF url.
  77. * @platform android
  78. */
  79. urlPrefixesForDefaultIntent?: $ReadOnlyArray<string>,
  80. |}>;
  81. /**
  82. * Renders a native WebView.
  83. */
  84. class WebView extends React.Component<WebViewPropsAndroid, State> {
  85. static defaultProps = {
  86. javaScriptEnabled: true,
  87. thirdPartyCookiesEnabled: true,
  88. scalesPageToFit: true,
  89. saveFormDataDisabled: false,
  90. originWhitelist: WebViewShared.defaultOriginWhitelist,
  91. };
  92. state = {
  93. viewState: WebViewState.IDLE,
  94. lastErrorEvent: null,
  95. startInLoadingState: true,
  96. };
  97. UNSAFE_componentWillMount() {
  98. if (this.props.startInLoadingState) {
  99. this.setState({ viewState: WebViewState.LOADING });
  100. }
  101. }
  102. render() {
  103. let otherView = null;
  104. if (this.state.viewState === WebViewState.LOADING) {
  105. otherView = (this.props.renderLoading || defaultRenderLoading)();
  106. } else if (this.state.viewState === WebViewState.ERROR) {
  107. const errorEvent = this.state.lastErrorEvent;
  108. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  109. otherView =
  110. this.props.renderError &&
  111. this.props.renderError(
  112. errorEvent.domain,
  113. errorEvent.code,
  114. errorEvent.description,
  115. );
  116. } else if (this.state.viewState !== WebViewState.IDLE) {
  117. console.error(
  118. 'RCTWebView invalid state encountered: ' + this.state.viewState,
  119. );
  120. }
  121. const webViewStyles = [styles.container, this.props.style];
  122. if (
  123. this.state.viewState === WebViewState.LOADING ||
  124. this.state.viewState === WebViewState.ERROR
  125. ) {
  126. // if we're in either LOADING or ERROR states, don't show the webView
  127. webViewStyles.push(styles.hidden);
  128. }
  129. let source: WebViewSource = this.props.source || {};
  130. if (!this.props.source && this.props.html) {
  131. source = { html: this.props.html };
  132. } else if (!this.props.source && this.props.url) {
  133. source = { uri: this.props.url };
  134. }
  135. if (source.method === 'POST' && source.headers) {
  136. console.warn(
  137. 'WebView: `source.headers` is not supported when using POST.',
  138. );
  139. } else if (source.method === 'GET' && source.body) {
  140. console.warn('WebView: `source.body` is not supported when using GET.');
  141. }
  142. const nativeConfig = this.props.nativeConfig || {};
  143. const originWhitelist = (this.props.originWhitelist || []).map(
  144. WebViewShared.originWhitelistToRegex,
  145. );
  146. let NativeWebView = nativeConfig.component || RCTWebView;
  147. const webView = (
  148. <NativeWebView
  149. ref={RCT_WEBVIEW_REF}
  150. key="webViewKey"
  151. style={webViewStyles}
  152. source={resolveAssetSource(source)}
  153. scalesPageToFit={this.props.scalesPageToFit}
  154. injectedJavaScript={this.props.injectedJavaScript}
  155. userAgent={this.props.userAgent}
  156. javaScriptEnabled={this.props.javaScriptEnabled}
  157. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  158. domStorageEnabled={this.props.domStorageEnabled}
  159. messagingEnabled={typeof this.props.onMessage === 'function'}
  160. onMessage={this.onMessage}
  161. contentInset={this.props.contentInset}
  162. automaticallyAdjustContentInsets={
  163. this.props.automaticallyAdjustContentInsets
  164. }
  165. onContentSizeChange={this.props.onContentSizeChange}
  166. onLoadingStart={this.onLoadingStart}
  167. onLoadingFinish={this.onLoadingFinish}
  168. onLoadingError={this.onLoadingError}
  169. testID={this.props.testID}
  170. geolocationEnabled={this.props.geolocationEnabled}
  171. mediaPlaybackRequiresUserAction={
  172. this.props.mediaPlaybackRequiresUserAction
  173. }
  174. allowUniversalAccessFromFileURLs={
  175. this.props.allowUniversalAccessFromFileURLs
  176. }
  177. originWhitelist={originWhitelist}
  178. mixedContentMode={this.props.mixedContentMode}
  179. saveFormDataDisabled={this.props.saveFormDataDisabled}
  180. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  181. {...nativeConfig.props}
  182. />
  183. );
  184. return (
  185. <View style={styles.container}>
  186. {webView}
  187. {otherView}
  188. </View>
  189. );
  190. }
  191. goForward = () => {
  192. UIManager.dispatchViewManagerCommand(
  193. this.getWebViewHandle(),
  194. UIManager.RCTWebView.Commands.goForward,
  195. null,
  196. );
  197. };
  198. goBack = () => {
  199. UIManager.dispatchViewManagerCommand(
  200. this.getWebViewHandle(),
  201. UIManager.RCTWebView.Commands.goBack,
  202. null,
  203. );
  204. };
  205. reload = () => {
  206. this.setState({
  207. viewState: WebViewState.LOADING,
  208. });
  209. UIManager.dispatchViewManagerCommand(
  210. this.getWebViewHandle(),
  211. UIManager.RCTWebView.Commands.reload,
  212. null,
  213. );
  214. };
  215. stopLoading = () => {
  216. UIManager.dispatchViewManagerCommand(
  217. this.getWebViewHandle(),
  218. UIManager.RCTWebView.Commands.stopLoading,
  219. null,
  220. );
  221. };
  222. postMessage = (data: string) => {
  223. UIManager.dispatchViewManagerCommand(
  224. this.getWebViewHandle(),
  225. UIManager.RCTWebView.Commands.postMessage,
  226. [String(data)],
  227. );
  228. };
  229. /**
  230. * Injects a javascript string into the referenced WebView. Deliberately does not
  231. * return a response because using eval() to return a response breaks this method
  232. * on pages with a Content Security Policy that disallows eval(). If you need that
  233. * functionality, look into postMessage/onMessage.
  234. */
  235. injectJavaScript = (data: string) => {
  236. UIManager.dispatchViewManagerCommand(
  237. this.getWebViewHandle(),
  238. UIManager.RCTWebView.Commands.injectJavaScript,
  239. [data],
  240. );
  241. };
  242. /**
  243. * We return an event with a bunch of fields including:
  244. * url, title, loading, canGoBack, canGoForward
  245. */
  246. updateNavigationState = (event: WebViewNavigationEvent) => {
  247. if (this.props.onNavigationStateChange) {
  248. this.props.onNavigationStateChange(event.nativeEvent);
  249. }
  250. };
  251. getWebViewHandle = () => {
  252. return ReactNative.findNodeHandle(this.refs[RCT_WEBVIEW_REF]);
  253. };
  254. onLoadingStart = (event: WebViewNavigationEvent) => {
  255. const onLoadStart = this.props.onLoadStart;
  256. onLoadStart && onLoadStart(event);
  257. this.updateNavigationState(event);
  258. };
  259. onLoadingError = (event: WebViewErrorEvent) => {
  260. event.persist(); // persist this event because we need to store it
  261. const { onError, onLoadEnd } = this.props;
  262. onError && onError(event);
  263. onLoadEnd && onLoadEnd(event);
  264. console.warn('Encountered an error loading page', event.nativeEvent);
  265. this.setState({
  266. lastErrorEvent: event.nativeEvent,
  267. viewState: WebViewState.ERROR,
  268. });
  269. };
  270. onLoadingFinish = (event: WebViewNavigationEvent) => {
  271. const { onLoad, onLoadEnd } = this.props;
  272. onLoad && onLoad(event);
  273. onLoadEnd && onLoadEnd(event);
  274. this.setState({
  275. viewState: WebViewState.IDLE,
  276. });
  277. this.updateNavigationState(event);
  278. };
  279. onMessage = (event: WebViewMessageEvent) => {
  280. const { onMessage } = this.props;
  281. onMessage && onMessage(event);
  282. };
  283. }
  284. const RCTWebView = requireNativeComponent('RCTWebView');
  285. const styles = StyleSheet.create({
  286. container: {
  287. flex: 1,
  288. },
  289. hidden: {
  290. height: 0,
  291. flex: 0, // disable 'flex:1' when hiding a View
  292. },
  293. loadingView: {
  294. flex: 1,
  295. justifyContent: 'center',
  296. alignItems: 'center',
  297. },
  298. loadingProgressBar: {
  299. height: 20,
  300. },
  301. });
  302. module.exports = WebView;