説明なし

WebView.android.js 8.2KB

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