No Description

WebView.android.js 8.3KB

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