react-native-webview.git

WebView.android.js 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. };
  64. static isFileUploadSupported = async () => {
  65. // native implementation should return "true" only for Android 5+
  66. return NativeModules.RNCWebView.isFileUploadSupported();
  67. }
  68. state = {
  69. viewState: this.props.startInLoadingState ? WebViewState.LOADING : WebViewState.IDLE,
  70. lastErrorEvent: null,
  71. };
  72. webViewRef = React.createRef();
  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. 'RNCWebView 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 || RNCWebView;
  118. const webView = (
  119. <NativeWebView
  120. ref={this.webViewRef}
  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. overScrollMode={this.props.overScrollMode}
  134. contentInset={this.props.contentInset}
  135. automaticallyAdjustContentInsets={
  136. this.props.automaticallyAdjustContentInsets
  137. }
  138. onContentSizeChange={this.props.onContentSizeChange}
  139. onLoadingStart={this.onLoadingStart}
  140. onLoadingFinish={this.onLoadingFinish}
  141. onLoadingError={this.onLoadingError}
  142. onLoadingProgress={this.onLoadingProgress}
  143. testID={this.props.testID}
  144. geolocationEnabled={this.props.geolocationEnabled}
  145. mediaPlaybackRequiresUserAction={
  146. this.props.mediaPlaybackRequiresUserAction
  147. }
  148. allowUniversalAccessFromFileURLs={
  149. this.props.allowUniversalAccessFromFileURLs
  150. }
  151. originWhitelist={originWhitelist}
  152. mixedContentMode={this.props.mixedContentMode}
  153. saveFormDataDisabled={this.props.saveFormDataDisabled}
  154. urlPrefixesForDefaultIntent={this.props.urlPrefixesForDefaultIntent}
  155. {...nativeConfig.props}
  156. />
  157. );
  158. return (
  159. <View style={styles.container}>
  160. {webView}
  161. {otherView}
  162. </View>
  163. );
  164. }
  165. goForward = () => {
  166. UIManager.dispatchViewManagerCommand(
  167. this.getWebViewHandle(),
  168. UIManager.RNCWebView.Commands.goForward,
  169. null,
  170. );
  171. };
  172. goBack = () => {
  173. UIManager.dispatchViewManagerCommand(
  174. this.getWebViewHandle(),
  175. UIManager.RNCWebView.Commands.goBack,
  176. null,
  177. );
  178. };
  179. reload = () => {
  180. this.setState({
  181. viewState: WebViewState.LOADING,
  182. });
  183. UIManager.dispatchViewManagerCommand(
  184. this.getWebViewHandle(),
  185. UIManager.RNCWebView.Commands.reload,
  186. null,
  187. );
  188. };
  189. stopLoading = () => {
  190. UIManager.dispatchViewManagerCommand(
  191. this.getWebViewHandle(),
  192. UIManager.RNCWebView.Commands.stopLoading,
  193. null,
  194. );
  195. };
  196. postMessage = (data: string) => {
  197. UIManager.dispatchViewManagerCommand(
  198. this.getWebViewHandle(),
  199. UIManager.RNCWebView.Commands.postMessage,
  200. [String(data)],
  201. );
  202. };
  203. /**
  204. * Injects a javascript string into the referenced WebView. Deliberately does not
  205. * return a response because using eval() to return a response breaks this method
  206. * on pages with a Content Security Policy that disallows eval(). If you need that
  207. * functionality, look into postMessage/onMessage.
  208. */
  209. injectJavaScript = (data: string) => {
  210. UIManager.dispatchViewManagerCommand(
  211. this.getWebViewHandle(),
  212. UIManager.RNCWebView.Commands.injectJavaScript,
  213. [data],
  214. );
  215. };
  216. /**
  217. * We return an event with a bunch of fields including:
  218. * url, title, loading, canGoBack, canGoForward
  219. */
  220. updateNavigationState = (event: WebViewNavigationEvent) => {
  221. if (this.props.onNavigationStateChange) {
  222. this.props.onNavigationStateChange(event.nativeEvent);
  223. }
  224. };
  225. getWebViewHandle = () => {
  226. return ReactNative.findNodeHandle(this.webViewRef.current);
  227. };
  228. onLoadingStart = (event: WebViewNavigationEvent) => {
  229. const onLoadStart = this.props.onLoadStart;
  230. onLoadStart && onLoadStart(event);
  231. this.updateNavigationState(event);
  232. };
  233. onLoadingError = (event: WebViewErrorEvent) => {
  234. event.persist(); // persist this event because we need to store it
  235. const { onError, onLoadEnd } = this.props;
  236. onError && onError(event);
  237. onLoadEnd && onLoadEnd(event);
  238. console.warn('Encountered an error loading page', event.nativeEvent);
  239. this.setState({
  240. lastErrorEvent: event.nativeEvent,
  241. viewState: WebViewState.ERROR,
  242. });
  243. };
  244. onLoadingFinish = (event: WebViewNavigationEvent) => {
  245. const { onLoad, onLoadEnd } = this.props;
  246. onLoad && onLoad(event);
  247. onLoadEnd && onLoadEnd(event);
  248. this.setState({
  249. viewState: WebViewState.IDLE,
  250. });
  251. this.updateNavigationState(event);
  252. };
  253. onMessage = (event: WebViewMessageEvent) => {
  254. const { onMessage } = this.props;
  255. onMessage && onMessage(event);
  256. };
  257. onLoadingProgress = (event: WebViewProgressEvent) => {
  258. const { onLoadProgress} = this.props;
  259. onLoadProgress && onLoadProgress(event);
  260. }
  261. }
  262. const RNCWebView = requireNativeComponent('RNCWebView');
  263. const styles = StyleSheet.create({
  264. container: {
  265. flex: 1,
  266. },
  267. hidden: {
  268. height: 0,
  269. flex: 0, // disable 'flex:1' when hiding a View
  270. },
  271. loadingView: {
  272. flex: 1,
  273. justifyContent: 'center',
  274. alignItems: 'center',
  275. },
  276. loadingProgressBar: {
  277. height: 20,
  278. },
  279. });
  280. module.exports = WebView;