Нема описа

WebView.android.js 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. originWhitelist: defaultOriginWhitelist,
  62. };
  63. static isFileUploadSupported = async () => {
  64. // native implementation should return "true" only for Android 5+
  65. return NativeModules.RNCWebView.isFileUploadSupported();
  66. }
  67. state = {
  68. viewState: this.props.startInLoadingState
  69. ? WebViewState.LOADING
  70. : WebViewState.IDLE,
  71. lastErrorEvent: null,
  72. };
  73. webViewRef = React.createRef();
  74. render() {
  75. let otherView = null;
  76. if (this.state.viewState === WebViewState.LOADING) {
  77. otherView = (this.props.renderLoading || defaultRenderLoading)();
  78. } else if (this.state.viewState === WebViewState.ERROR) {
  79. const errorEvent = this.state.lastErrorEvent;
  80. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  81. otherView =
  82. this.props.renderError &&
  83. this.props.renderError(
  84. errorEvent.domain,
  85. errorEvent.code,
  86. errorEvent.description,
  87. );
  88. } else if (this.state.viewState !== WebViewState.IDLE) {
  89. console.error(
  90. 'RNCWebView invalid state encountered: ' + this.state.viewState,
  91. );
  92. }
  93. const webViewStyles = [styles.container, this.props.style];
  94. if (
  95. this.state.viewState === WebViewState.LOADING ||
  96. this.state.viewState === WebViewState.ERROR
  97. ) {
  98. // if we're in either LOADING or ERROR states, don't show the webView
  99. webViewStyles.push(styles.hidden);
  100. }
  101. let source: WebViewSource = this.props.source || {};
  102. if (!this.props.source && this.props.html) {
  103. source = { html: this.props.html };
  104. } else if (!this.props.source && this.props.url) {
  105. source = { uri: this.props.url };
  106. }
  107. if (source.method === 'POST' && source.headers) {
  108. console.warn(
  109. 'WebView: `source.headers` is not supported when using POST.',
  110. );
  111. } else if (source.method === 'GET' && source.body) {
  112. console.warn('WebView: `source.body` is not supported when using GET.');
  113. }
  114. const nativeConfig = this.props.nativeConfig || {};
  115. let NativeWebView = nativeConfig.component || RNCWebView;
  116. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  117. this.onShouldStartLoadWithRequestCallback,
  118. this.props.originWhitelist,
  119. this.props.onShouldStartLoadWithRequest,
  120. );
  121. const webView = (
  122. <NativeWebView
  123. ref={this.webViewRef}
  124. key="webViewKey"
  125. style={webViewStyles}
  126. source={resolveAssetSource(source)}
  127. scalesPageToFit={this.props.scalesPageToFit}
  128. allowFileAccess={this.props.allowFileAccess}
  129. injectedJavaScript={this.props.injectedJavaScript}
  130. userAgent={this.props.userAgent}
  131. javaScriptEnabled={this.props.javaScriptEnabled}
  132. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  133. domStorageEnabled={this.props.domStorageEnabled}
  134. messagingEnabled={typeof this.props.onMessage === 'function'}
  135. onMessage={this.onMessage}
  136. overScrollMode={this.props.overScrollMode}
  137. contentInset={this.props.contentInset}
  138. automaticallyAdjustContentInsets={
  139. this.props.automaticallyAdjustContentInsets
  140. }
  141. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  142. onContentSizeChange={this.props.onContentSizeChange}
  143. onLoadingStart={this.onLoadingStart}
  144. onLoadingFinish={this.onLoadingFinish}
  145. onLoadingError={this.onLoadingError}
  146. onLoadingProgress={this.onLoadingProgress}
  147. testID={this.props.testID}
  148. geolocationEnabled={this.props.geolocationEnabled}
  149. mediaPlaybackRequiresUserAction={
  150. this.props.mediaPlaybackRequiresUserAction
  151. }
  152. allowUniversalAccessFromFileURLs={
  153. this.props.allowUniversalAccessFromFileURLs
  154. }
  155. mixedContentMode={this.props.mixedContentMode}
  156. saveFormDataDisabled={this.props.saveFormDataDisabled}
  157. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  158. {...nativeConfig.props}
  159. />
  160. );
  161. return (
  162. <View style={styles.container}>
  163. {webView}
  164. {otherView}
  165. </View>
  166. );
  167. }
  168. goForward = () => {
  169. UIManager.dispatchViewManagerCommand(
  170. this.getWebViewHandle(),
  171. UIManager.RNCWebView.Commands.goForward,
  172. null,
  173. );
  174. };
  175. goBack = () => {
  176. UIManager.dispatchViewManagerCommand(
  177. this.getWebViewHandle(),
  178. UIManager.RNCWebView.Commands.goBack,
  179. null,
  180. );
  181. };
  182. reload = () => {
  183. this.setState({
  184. viewState: WebViewState.LOADING,
  185. });
  186. UIManager.dispatchViewManagerCommand(
  187. this.getWebViewHandle(),
  188. UIManager.RNCWebView.Commands.reload,
  189. null,
  190. );
  191. };
  192. stopLoading = () => {
  193. UIManager.dispatchViewManagerCommand(
  194. this.getWebViewHandle(),
  195. UIManager.RNCWebView.Commands.stopLoading,
  196. null,
  197. );
  198. };
  199. postMessage = (data: string) => {
  200. UIManager.dispatchViewManagerCommand(
  201. this.getWebViewHandle(),
  202. UIManager.RNCWebView.Commands.postMessage,
  203. [String(data)],
  204. );
  205. };
  206. /**
  207. * Injects a javascript string into the referenced WebView. Deliberately does not
  208. * return a response because using eval() to return a response breaks this method
  209. * on pages with a Content Security Policy that disallows eval(). If you need that
  210. * functionality, look into postMessage/onMessage.
  211. */
  212. injectJavaScript = (data: string) => {
  213. UIManager.dispatchViewManagerCommand(
  214. this.getWebViewHandle(),
  215. UIManager.RNCWebView.Commands.injectJavaScript,
  216. [data],
  217. );
  218. };
  219. /**
  220. * We return an event with a bunch of fields including:
  221. * url, title, loading, canGoBack, canGoForward
  222. */
  223. updateNavigationState = (event: WebViewNavigationEvent) => {
  224. if (this.props.onNavigationStateChange) {
  225. this.props.onNavigationStateChange(event.nativeEvent);
  226. }
  227. };
  228. getWebViewHandle = () => {
  229. return ReactNative.findNodeHandle(this.webViewRef.current);
  230. };
  231. onLoadingStart = (event: WebViewNavigationEvent) => {
  232. const onLoadStart = this.props.onLoadStart;
  233. onLoadStart && onLoadStart(event);
  234. this.updateNavigationState(event);
  235. };
  236. onLoadingError = (event: WebViewErrorEvent) => {
  237. event.persist(); // persist this event because we need to store it
  238. const { onError, onLoadEnd } = this.props;
  239. onError && onError(event);
  240. onLoadEnd && onLoadEnd(event);
  241. console.warn('Encountered an error loading page', event.nativeEvent);
  242. this.setState({
  243. lastErrorEvent: event.nativeEvent,
  244. viewState: WebViewState.ERROR,
  245. });
  246. };
  247. onLoadingFinish = (event: WebViewNavigationEvent) => {
  248. const { onLoad, onLoadEnd } = this.props;
  249. onLoad && onLoad(event);
  250. onLoadEnd && onLoadEnd(event);
  251. this.setState({
  252. viewState: WebViewState.IDLE,
  253. });
  254. this.updateNavigationState(event);
  255. };
  256. onMessage = (event: WebViewMessageEvent) => {
  257. const { onMessage } = this.props;
  258. onMessage && onMessage(event);
  259. };
  260. onLoadingProgress = (event: WebViewProgressEvent) => {
  261. const { onLoadProgress } = this.props;
  262. onLoadProgress && onLoadProgress(event);
  263. };
  264. onShouldStartLoadWithRequestCallback = (
  265. shouldStart: boolean,
  266. url: string,
  267. ) => {
  268. if (shouldStart) {
  269. UIManager.dispatchViewManagerCommand(
  270. this.getWebViewHandle(),
  271. UIManager.RNCWebView.Commands.loadUrl,
  272. [String(url)],
  273. );
  274. }
  275. };
  276. }
  277. const RNCWebView = requireNativeComponent('RNCWebView');
  278. const styles = StyleSheet.create({
  279. container: {
  280. flex: 1,
  281. },
  282. hidden: {
  283. height: 0,
  284. flex: 0, // disable 'flex:1' when hiding a View
  285. },
  286. loadingView: {
  287. flex: 1,
  288. justifyContent: 'center',
  289. alignItems: 'center',
  290. },
  291. loadingProgressBar: {
  292. height: 20,
  293. },
  294. });
  295. module.exports = WebView;