react-native-webview.git

WebView.android.js 8.4KB

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