Ingen beskrivning

WebView.android.js 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. showsHorizontalScrollIndicator={this.props.showsHorizontalScrollIndicator}
  165. showsVerticalScrollIndicator={this.props.showsVerticalScrollIndicator}
  166. {...nativeConfig.props}
  167. />
  168. );
  169. return (
  170. <View style={styles.container}>
  171. {webView}
  172. {otherView}
  173. </View>
  174. );
  175. }
  176. getViewManagerConfig = (viewManagerName: string) => {
  177. if (!UIManager.getViewManagerConfig) {
  178. return UIManager[viewManagerName];
  179. }
  180. return UIManager.getViewManagerConfig(viewManagerName);
  181. };
  182. getCommands = () => this.getViewManagerConfig('RNCWebView').Commands;
  183. goForward = () => {
  184. UIManager.dispatchViewManagerCommand(
  185. this.getWebViewHandle(),
  186. this.getCommands().goForward,
  187. null,
  188. );
  189. };
  190. goBack = () => {
  191. UIManager.dispatchViewManagerCommand(
  192. this.getWebViewHandle(),
  193. this.getCommands().goBack,
  194. null,
  195. );
  196. };
  197. reload = () => {
  198. this.setState({
  199. viewState: WebViewState.LOADING,
  200. });
  201. UIManager.dispatchViewManagerCommand(
  202. this.getWebViewHandle(),
  203. this.getCommands().reload,
  204. null,
  205. );
  206. };
  207. stopLoading = () => {
  208. UIManager.dispatchViewManagerCommand(
  209. this.getWebViewHandle(),
  210. this.getCommands().stopLoading,
  211. null,
  212. );
  213. };
  214. postMessage = (data: string) => {
  215. UIManager.dispatchViewManagerCommand(
  216. this.getWebViewHandle(),
  217. this.getCommands().postMessage,
  218. [String(data)],
  219. );
  220. };
  221. /**
  222. * Injects a javascript string into the referenced WebView. Deliberately does not
  223. * return a response because using eval() to return a response breaks this method
  224. * on pages with a Content Security Policy that disallows eval(). If you need that
  225. * functionality, look into postMessage/onMessage.
  226. */
  227. injectJavaScript = (data: string) => {
  228. UIManager.dispatchViewManagerCommand(
  229. this.getWebViewHandle(),
  230. this.getCommands().injectJavaScript,
  231. [data],
  232. );
  233. };
  234. /**
  235. * We return an event with a bunch of fields including:
  236. * url, title, loading, canGoBack, canGoForward
  237. */
  238. updateNavigationState = (event: WebViewNavigationEvent) => {
  239. if (this.props.onNavigationStateChange) {
  240. this.props.onNavigationStateChange(event.nativeEvent);
  241. }
  242. };
  243. getWebViewHandle = () => {
  244. return ReactNative.findNodeHandle(this.webViewRef.current);
  245. };
  246. onLoadingStart = (event: WebViewNavigationEvent) => {
  247. const onLoadStart = this.props.onLoadStart;
  248. onLoadStart && onLoadStart(event);
  249. this.updateNavigationState(event);
  250. };
  251. onLoadingError = (event: WebViewErrorEvent) => {
  252. event.persist(); // persist this event because we need to store it
  253. const { onError, onLoadEnd } = this.props;
  254. onError && onError(event);
  255. onLoadEnd && onLoadEnd(event);
  256. console.warn('Encountered an error loading page', event.nativeEvent);
  257. this.setState({
  258. lastErrorEvent: event.nativeEvent,
  259. viewState: WebViewState.ERROR,
  260. });
  261. };
  262. onLoadingFinish = (event: WebViewNavigationEvent) => {
  263. const { onLoad, onLoadEnd } = this.props;
  264. onLoad && onLoad(event);
  265. onLoadEnd && onLoadEnd(event);
  266. this.setState({
  267. viewState: WebViewState.IDLE,
  268. });
  269. this.updateNavigationState(event);
  270. };
  271. onMessage = (event: WebViewMessageEvent) => {
  272. const { onMessage } = this.props;
  273. onMessage && onMessage(event);
  274. };
  275. onLoadingProgress = (event: WebViewProgressEvent) => {
  276. const { onLoadProgress } = this.props;
  277. onLoadProgress && onLoadProgress(event);
  278. };
  279. onShouldStartLoadWithRequestCallback = (
  280. shouldStart: boolean,
  281. url: string,
  282. ) => {
  283. if (shouldStart) {
  284. UIManager.dispatchViewManagerCommand(
  285. this.getWebViewHandle(),
  286. this.getCommands().loadUrl,
  287. [String(url)],
  288. );
  289. }
  290. };
  291. }
  292. const RNCWebView = requireNativeComponent('RNCWebView');
  293. const styles = StyleSheet.create({
  294. container: {
  295. flex: 1,
  296. },
  297. hidden: {
  298. height: 0,
  299. flex: 0, // disable 'flex:1' when hiding a View
  300. },
  301. loadingView: {
  302. flex: 1,
  303. justifyContent: 'center',
  304. alignItems: 'center',
  305. },
  306. loadingProgressBar: {
  307. height: 20,
  308. },
  309. });
  310. module.exports = WebView;