Нет описания

WebView.android.js 8.5KB

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