react-native-webview.git

WebView.android.js 9.3KB

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