react-native-webview.git

WebView.android.js 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. NativeModules
  21. } from 'react-native';
  22. import invariant from 'fbjs/lib/invariant';
  23. import keyMirror from 'fbjs/lib/keyMirror';
  24. import WebViewShared from './WebViewShared';
  25. import type {
  26. WebViewEvent,
  27. WebViewError,
  28. WebViewErrorEvent,
  29. WebViewMessageEvent,
  30. WebViewNavigation,
  31. WebViewNavigationEvent,
  32. WebViewSharedProps,
  33. WebViewSource,
  34. WebViewProgressEvent,
  35. } from './WebViewTypes';
  36. const resolveAssetSource = Image.resolveAssetSource;
  37. const WebViewState = keyMirror({
  38. IDLE: null,
  39. LOADING: null,
  40. ERROR: null,
  41. });
  42. const defaultRenderLoading = () => (
  43. <View style={styles.loadingView}>
  44. <ActivityIndicator style={styles.loadingProgressBar} />
  45. </View>
  46. );
  47. type State = {|
  48. viewState: WebViewState,
  49. lastErrorEvent: ?WebViewError,
  50. |};
  51. /**
  52. * Renders a native WebView.
  53. */
  54. class WebView extends React.Component<WebViewSharedProps, State> {
  55. static defaultProps = {
  56. overScrollMode: 'always',
  57. javaScriptEnabled: true,
  58. thirdPartyCookiesEnabled: true,
  59. scalesPageToFit: true,
  60. allowFileAccess: false,
  61. saveFormDataDisabled: false,
  62. originWhitelist: WebViewShared.defaultOriginWhitelist,
  63. enableCache: true,
  64. };
  65. static isFileUploadSupported = async () => {
  66. // native implementation should return "true" only for Android 5+
  67. return NativeModules.RNCWebView.isFileUploadSupported();
  68. }
  69. state = {
  70. viewState: this.props.startInLoadingState ? WebViewState.LOADING : 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. const originWhitelist = (this.props.originWhitelist || []).map(
  116. WebViewShared.originWhitelistToRegex,
  117. );
  118. let NativeWebView = nativeConfig.component || RNCWebView;
  119. const webView = (
  120. <NativeWebView
  121. ref={this.webViewRef}
  122. key="webViewKey"
  123. style={webViewStyles}
  124. source={resolveAssetSource(source)}
  125. scalesPageToFit={this.props.scalesPageToFit}
  126. allowFileAccess={this.props.allowFileAccess}
  127. injectedJavaScript={this.props.injectedJavaScript}
  128. userAgent={this.props.userAgent}
  129. javaScriptEnabled={this.props.javaScriptEnabled}
  130. thirdPartyCookiesEnabled={this.props.thirdPartyCookiesEnabled}
  131. domStorageEnabled={this.props.domStorageEnabled}
  132. messagingEnabled={typeof this.props.onMessage === 'function'}
  133. onMessage={this.onMessage}
  134. overScrollMode={this.props.overScrollMode}
  135. contentInset={this.props.contentInset}
  136. automaticallyAdjustContentInsets={
  137. this.props.automaticallyAdjustContentInsets
  138. }
  139. onContentSizeChange={this.props.onContentSizeChange}
  140. onLoadingStart={this.onLoadingStart}
  141. onLoadingFinish={this.onLoadingFinish}
  142. onLoadingError={this.onLoadingError}
  143. onLoadingProgress={this.onLoadingProgress}
  144. testID={this.props.testID}
  145. geolocationEnabled={this.props.geolocationEnabled}
  146. mediaPlaybackRequiresUserAction={
  147. this.props.mediaPlaybackRequiresUserAction
  148. }
  149. allowUniversalAccessFromFileURLs={
  150. this.props.allowUniversalAccessFromFileURLs
  151. }
  152. originWhitelist={originWhitelist}
  153. mixedContentMode={this.props.mixedContentMode}
  154. saveFormDataDisabled={this.props.saveFormDataDisabled}
  155. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  156. {...nativeConfig.props}
  157. />
  158. );
  159. return (
  160. <View style={styles.container}>
  161. {webView}
  162. {otherView}
  163. </View>
  164. );
  165. }
  166. goForward = () => {
  167. UIManager.dispatchViewManagerCommand(
  168. this.getWebViewHandle(),
  169. UIManager.RNCWebView.Commands.goForward,
  170. null,
  171. );
  172. };
  173. goBack = () => {
  174. UIManager.dispatchViewManagerCommand(
  175. this.getWebViewHandle(),
  176. UIManager.RNCWebView.Commands.goBack,
  177. null,
  178. );
  179. };
  180. reload = () => {
  181. this.setState({
  182. viewState: WebViewState.LOADING,
  183. });
  184. UIManager.dispatchViewManagerCommand(
  185. this.getWebViewHandle(),
  186. UIManager.RNCWebView.Commands.reload,
  187. null,
  188. );
  189. };
  190. stopLoading = () => {
  191. UIManager.dispatchViewManagerCommand(
  192. this.getWebViewHandle(),
  193. UIManager.RNCWebView.Commands.stopLoading,
  194. null,
  195. );
  196. };
  197. postMessage = (data: string) => {
  198. UIManager.dispatchViewManagerCommand(
  199. this.getWebViewHandle(),
  200. UIManager.RNCWebView.Commands.postMessage,
  201. [String(data)],
  202. );
  203. };
  204. /**
  205. * Injects a javascript string into the referenced WebView. Deliberately does not
  206. * return a response because using eval() to return a response breaks this method
  207. * on pages with a Content Security Policy that disallows eval(). If you need that
  208. * functionality, look into postMessage/onMessage.
  209. */
  210. injectJavaScript = (data: string) => {
  211. UIManager.dispatchViewManagerCommand(
  212. this.getWebViewHandle(),
  213. UIManager.RNCWebView.Commands.injectJavaScript,
  214. [data],
  215. );
  216. };
  217. /**
  218. * We return an event with a bunch of fields including:
  219. * url, title, loading, canGoBack, canGoForward
  220. */
  221. updateNavigationState = (event: WebViewNavigationEvent) => {
  222. if (this.props.onNavigationStateChange) {
  223. this.props.onNavigationStateChange(event.nativeEvent);
  224. }
  225. };
  226. getWebViewHandle = () => {
  227. return ReactNative.findNodeHandle(this.webViewRef.current);
  228. };
  229. onLoadingStart = (event: WebViewNavigationEvent) => {
  230. const onLoadStart = this.props.onLoadStart;
  231. onLoadStart && onLoadStart(event);
  232. this.updateNavigationState(event);
  233. };
  234. onLoadingError = (event: WebViewErrorEvent) => {
  235. event.persist(); // persist this event because we need to store it
  236. const { onError, onLoadEnd } = this.props;
  237. onError && onError(event);
  238. onLoadEnd && onLoadEnd(event);
  239. console.warn('Encountered an error loading page', event.nativeEvent);
  240. this.setState({
  241. lastErrorEvent: event.nativeEvent,
  242. viewState: WebViewState.ERROR,
  243. });
  244. };
  245. onLoadingFinish = (event: WebViewNavigationEvent) => {
  246. const { onLoad, onLoadEnd } = this.props;
  247. onLoad && onLoad(event);
  248. onLoadEnd && onLoadEnd(event);
  249. this.setState({
  250. viewState: WebViewState.IDLE,
  251. });
  252. this.updateNavigationState(event);
  253. };
  254. onMessage = (event: WebViewMessageEvent) => {
  255. const { onMessage } = this.props;
  256. onMessage && onMessage(event);
  257. };
  258. onLoadingProgress = (event: WebViewProgressEvent) => {
  259. const { onLoadProgress} = this.props;
  260. onLoadProgress && onLoadProgress(event);
  261. }
  262. }
  263. const RNCWebView = requireNativeComponent('RNCWebView');
  264. const styles = StyleSheet.create({
  265. container: {
  266. flex: 1,
  267. },
  268. hidden: {
  269. height: 0,
  270. flex: 0, // disable 'flex:1' when hiding a View
  271. },
  272. loadingView: {
  273. flex: 1,
  274. justifyContent: 'center',
  275. alignItems: 'center',
  276. },
  277. loadingProgressBar: {
  278. height: 20,
  279. },
  280. });
  281. module.exports = WebView;