No Description

WebView.android.js 8.4KB

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