説明なし

WebView.ios.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 {
  12. ActivityIndicator,
  13. Linking,
  14. StyleSheet,
  15. Text,
  16. UIManager,
  17. View,
  18. requireNativeComponent,
  19. NativeModules,
  20. Image,
  21. findNodeHandle,
  22. } from 'react-native';
  23. import invariant from 'fbjs/lib/invariant';
  24. import keyMirror from 'fbjs/lib/keyMirror';
  25. import {
  26. defaultOriginWhitelist,
  27. createOnShouldStartLoadWithRequest,
  28. } from './WebViewShared';
  29. import type {
  30. WebViewEvent,
  31. WebViewError,
  32. WebViewErrorEvent,
  33. WebViewMessageEvent,
  34. WebViewNavigationEvent,
  35. WebViewSharedProps,
  36. WebViewSource,
  37. WebViewProgressEvent,
  38. } from './WebViewTypes';
  39. const resolveAssetSource = Image.resolveAssetSource;
  40. // Imported from https://github.com/facebook/react-native/blob/master/Libraries/Components/ScrollView/processDecelerationRate.js
  41. function processDecelerationRate(decelerationRate) {
  42. if (decelerationRate === 'normal') {
  43. decelerationRate = 0.998;
  44. } else if (decelerationRate === 'fast') {
  45. decelerationRate = 0.99;
  46. }
  47. return decelerationRate;
  48. }
  49. const RNCUIWebViewManager = NativeModules.RNCUIWebViewManager;
  50. const RNCWKWebViewManager = NativeModules.RNCWKWebViewManager;
  51. const BGWASH = 'rgba(255,255,255,0.8)';
  52. const WebViewState = keyMirror({
  53. IDLE: null,
  54. LOADING: null,
  55. ERROR: null,
  56. });
  57. const NavigationType = keyMirror({
  58. click: true,
  59. formsubmit: true,
  60. backforward: true,
  61. reload: true,
  62. formresubmit: true,
  63. other: true,
  64. });
  65. const JSNavigationScheme = 'react-js-navigation';
  66. type State = {|
  67. viewState: WebViewState,
  68. lastErrorEvent: ?WebViewError,
  69. |};
  70. const DataDetectorTypes = [
  71. 'phoneNumber',
  72. 'link',
  73. 'address',
  74. 'calendarEvent',
  75. 'trackingNumber',
  76. 'flightNumber',
  77. 'lookupSuggestion',
  78. 'none',
  79. 'all',
  80. ];
  81. const defaultRenderLoading = () => (
  82. <View style={styles.loadingView}>
  83. <ActivityIndicator />
  84. </View>
  85. );
  86. const defaultRenderError = (errorDomain, errorCode, errorDesc) => (
  87. <View style={styles.errorContainer}>
  88. <Text style={styles.errorTextTitle}>Error loading page</Text>
  89. <Text style={styles.errorText}>{'Domain: ' + errorDomain}</Text>
  90. <Text style={styles.errorText}>{'Error Code: ' + errorCode}</Text>
  91. <Text style={styles.errorText}>{'Description: ' + errorDesc}</Text>
  92. </View>
  93. );
  94. /**
  95. * `WebView` renders web content in a native view.
  96. *
  97. *```
  98. * import React, { Component } from 'react';
  99. * import { WebView } from 'react-native';
  100. *
  101. * class MyWeb extends Component {
  102. * render() {
  103. * return (
  104. * <WebView
  105. * source={{uri: 'https://github.com/facebook/react-native'}}
  106. * style={{marginTop: 20}}
  107. * />
  108. * );
  109. * }
  110. * }
  111. *```
  112. *
  113. * You can use this component to navigate back and forth in the web view's
  114. * history and configure various properties for the web content.
  115. */
  116. class WebView extends React.Component<WebViewSharedProps, State> {
  117. static JSNavigationScheme = JSNavigationScheme;
  118. static NavigationType = NavigationType;
  119. static defaultProps = {
  120. useWebKit: true,
  121. originWhitelist: defaultOriginWhitelist,
  122. useSharedProcessPool: true,
  123. };
  124. static isFileUploadSupported = async () => {
  125. // no native implementation for iOS, depends only on permissions
  126. return true;
  127. }
  128. state = {
  129. viewState: this.props.startInLoadingState
  130. ? WebViewState.LOADING
  131. : WebViewState.IDLE,
  132. lastErrorEvent: null,
  133. };
  134. webViewRef = React.createRef();
  135. UNSAFE_componentWillMount() {
  136. if (
  137. this.props.useWebKit === true &&
  138. this.props.scalesPageToFit !== undefined
  139. ) {
  140. console.warn(
  141. 'The scalesPageToFit property is not supported when useWebKit = true',
  142. );
  143. }
  144. if (
  145. !this.props.useWebKit &&
  146. this.props.allowsBackForwardNavigationGestures
  147. ) {
  148. console.warn(
  149. 'The allowsBackForwardNavigationGestures property is not supported when useWebKit = false',
  150. );
  151. }
  152. }
  153. render() {
  154. let otherView = null;
  155. let scalesPageToFit;
  156. if (this.props.useWebKit) {
  157. ({ scalesPageToFit } = this.props);
  158. } else {
  159. ({ scalesPageToFit = true } = this.props);
  160. }
  161. if (this.state.viewState === WebViewState.LOADING) {
  162. otherView = (this.props.renderLoading || defaultRenderLoading)();
  163. } else if (this.state.viewState === WebViewState.ERROR) {
  164. const errorEvent = this.state.lastErrorEvent;
  165. invariant(errorEvent != null, 'lastErrorEvent expected to be non-null');
  166. otherView = (this.props.renderError || defaultRenderError)(
  167. errorEvent.domain,
  168. errorEvent.code,
  169. errorEvent.description,
  170. );
  171. } else if (this.state.viewState !== WebViewState.IDLE) {
  172. console.error(
  173. 'RNCWebView invalid state encountered: ' + this.state.viewState,
  174. );
  175. }
  176. const webViewStyles = [styles.container, styles.webView, this.props.style];
  177. if (
  178. this.state.viewState === WebViewState.LOADING ||
  179. this.state.viewState === WebViewState.ERROR
  180. ) {
  181. // if we're in either LOADING or ERROR states, don't show the webView
  182. webViewStyles.push(styles.hidden);
  183. }
  184. const nativeConfig = this.props.nativeConfig || {};
  185. const onShouldStartLoadWithRequest = createOnShouldStartLoadWithRequest(
  186. this.onShouldStartLoadWithRequestCallback,
  187. this.props.originWhitelist,
  188. this.props.onShouldStartLoadWithRequest,
  189. );
  190. const decelerationRate = processDecelerationRate(
  191. this.props.decelerationRate,
  192. );
  193. let source: WebViewSource = this.props.source || {};
  194. if (!this.props.source && this.props.html) {
  195. source = { html: this.props.html };
  196. } else if (!this.props.source && this.props.url) {
  197. source = { uri: this.props.url };
  198. }
  199. const messagingEnabled = typeof this.props.onMessage === 'function';
  200. let NativeWebView = nativeConfig.component;
  201. if (this.props.useWebKit) {
  202. NativeWebView = NativeWebView || RNCWKWebView;
  203. } else {
  204. NativeWebView = NativeWebView || RNCUIWebView;
  205. }
  206. const webView = (
  207. <NativeWebView
  208. ref={this.webViewRef}
  209. key="webViewKey"
  210. style={webViewStyles}
  211. source={resolveAssetSource(source)}
  212. injectedJavaScript={this.props.injectedJavaScript}
  213. bounces={this.props.bounces}
  214. scrollEnabled={this.props.scrollEnabled}
  215. pagingEnabled={this.props.pagingEnabled}
  216. decelerationRate={decelerationRate}
  217. contentInset={this.props.contentInset}
  218. automaticallyAdjustContentInsets={
  219. this.props.automaticallyAdjustContentInsets
  220. }
  221. hideKeyboardAccessoryView={this.props.hideKeyboardAccessoryView}
  222. allowsBackForwardNavigationGestures={this.props.allowsBackForwardNavigationGestures}
  223. userAgent={this.props.userAgent}
  224. onLoadingStart={this._onLoadingStart}
  225. onLoadingFinish={this._onLoadingFinish}
  226. onLoadingError={this._onLoadingError}
  227. onLoadingProgress={this._onLoadingProgress}
  228. messagingEnabled={messagingEnabled}
  229. onMessage={this._onMessage}
  230. onShouldStartLoadWithRequest={onShouldStartLoadWithRequest}
  231. scalesPageToFit={scalesPageToFit}
  232. allowsInlineMediaPlayback={this.props.allowsInlineMediaPlayback}
  233. mediaPlaybackRequiresUserAction={
  234. this.props.mediaPlaybackRequiresUserAction
  235. }
  236. dataDetectorTypes={this.props.dataDetectorTypes}
  237. useSharedProcessPool={this.props.useSharedProcessPool}
  238. allowsLinkPreview={this.props.allowsLinkPreview}
  239. {...nativeConfig.props}
  240. />
  241. );
  242. return (
  243. <View style={styles.container}>
  244. {webView}
  245. {otherView}
  246. </View>
  247. );
  248. }
  249. _getCommands() {
  250. if (!this.props.useWebKit) {
  251. return UIManager.RNCUIWebView.Commands;
  252. }
  253. return UIManager.RNCWKWebView.Commands;
  254. }
  255. /**
  256. * Go forward one page in the web view's history.
  257. */
  258. goForward = () => {
  259. UIManager.dispatchViewManagerCommand(
  260. this.getWebViewHandle(),
  261. this._getCommands().goForward,
  262. null,
  263. );
  264. };
  265. /**
  266. * Go back one page in the web view's history.
  267. */
  268. goBack = () => {
  269. UIManager.dispatchViewManagerCommand(
  270. this.getWebViewHandle(),
  271. this._getCommands().goBack,
  272. null,
  273. );
  274. };
  275. /**
  276. * Reloads the current page.
  277. */
  278. reload = () => {
  279. this.setState({ viewState: WebViewState.LOADING });
  280. UIManager.dispatchViewManagerCommand(
  281. this.getWebViewHandle(),
  282. this._getCommands().reload,
  283. null,
  284. );
  285. };
  286. /**
  287. * Stop loading the current page.
  288. */
  289. stopLoading = () => {
  290. UIManager.dispatchViewManagerCommand(
  291. this.getWebViewHandle(),
  292. this._getCommands().stopLoading,
  293. null,
  294. );
  295. };
  296. /**
  297. * Posts a message to the web view, which will emit a `message` event.
  298. * Accepts one argument, `data`, which must be a string.
  299. *
  300. * In your webview, you'll need to something like the following.
  301. *
  302. * ```js
  303. * document.addEventListener('message', e => { document.title = e.data; });
  304. * ```
  305. */
  306. postMessage = (data: string) => {
  307. UIManager.dispatchViewManagerCommand(
  308. this.getWebViewHandle(),
  309. this._getCommands().postMessage,
  310. [String(data)],
  311. );
  312. };
  313. /**
  314. * Injects a javascript string into the referenced WebView. Deliberately does not
  315. * return a response because using eval() to return a response breaks this method
  316. * on pages with a Content Security Policy that disallows eval(). If you need that
  317. * functionality, look into postMessage/onMessage.
  318. */
  319. injectJavaScript = (data: string) => {
  320. UIManager.dispatchViewManagerCommand(
  321. this.getWebViewHandle(),
  322. this._getCommands().injectJavaScript,
  323. [data],
  324. );
  325. };
  326. /**
  327. * We return an event with a bunch of fields including:
  328. * url, title, loading, canGoBack, canGoForward
  329. */
  330. _updateNavigationState = (event: WebViewNavigationEvent) => {
  331. if (this.props.onNavigationStateChange) {
  332. this.props.onNavigationStateChange(event.nativeEvent);
  333. }
  334. };
  335. /**
  336. * Returns the native `WebView` node.
  337. */
  338. getWebViewHandle = () => {
  339. return findNodeHandle(this.webViewRef.current);
  340. };
  341. _onLoadingStart = (event: WebViewNavigationEvent) => {
  342. const onLoadStart = this.props.onLoadStart;
  343. onLoadStart && onLoadStart(event);
  344. this._updateNavigationState(event);
  345. };
  346. _onLoadingError = (event: WebViewErrorEvent) => {
  347. event.persist(); // persist this event because we need to store it
  348. const { onError, onLoadEnd } = this.props;
  349. onError && onError(event);
  350. onLoadEnd && onLoadEnd(event);
  351. console.warn('Encountered an error loading page', event.nativeEvent);
  352. this.setState({
  353. lastErrorEvent: event.nativeEvent,
  354. viewState: WebViewState.ERROR,
  355. });
  356. };
  357. _onLoadingFinish = (event: WebViewNavigationEvent) => {
  358. const { onLoad, onLoadEnd } = this.props;
  359. onLoad && onLoad(event);
  360. onLoadEnd && onLoadEnd(event);
  361. this.setState({
  362. viewState: WebViewState.IDLE,
  363. });
  364. this._updateNavigationState(event);
  365. };
  366. _onMessage = (event: WebViewMessageEvent) => {
  367. const { onMessage } = this.props;
  368. onMessage && onMessage(event);
  369. };
  370. _onLoadingProgress = (event: WebViewProgressEvent) => {
  371. const { onLoadProgress } = this.props;
  372. onLoadProgress && onLoadProgress(event);
  373. };
  374. onShouldStartLoadWithRequestCallback = (
  375. shouldStart: boolean,
  376. url: string,
  377. lockIdentifier: number,
  378. ) => {
  379. let viewManager = (this.props.nativeConfig || {}).viewManager;
  380. if (this.props.useWebKit) {
  381. viewManager = viewManager || RNCWKWebViewManager;
  382. } else {
  383. viewManager = viewManager || RNCUIWebViewManager;
  384. }
  385. invariant(viewManager != null, 'viewManager expected to be non-null');
  386. viewManager.startLoadWithResult(!!shouldStart, lockIdentifier);
  387. };
  388. componentDidUpdate(prevProps: WebViewSharedProps) {
  389. if (!(prevProps.useWebKit && this.props.useWebKit)) {
  390. return;
  391. }
  392. this._showRedboxOnPropChanges(prevProps, 'allowsInlineMediaPlayback');
  393. this._showRedboxOnPropChanges(prevProps, 'mediaPlaybackRequiresUserAction');
  394. this._showRedboxOnPropChanges(prevProps, 'dataDetectorTypes');
  395. if (this.props.scalesPageToFit !== undefined) {
  396. console.warn(
  397. 'The scalesPageToFit property is not supported when useWebKit = true',
  398. );
  399. }
  400. }
  401. _showRedboxOnPropChanges(prevProps, propName: string) {
  402. if (this.props[propName] !== prevProps[propName]) {
  403. console.error(
  404. `Changes to property ${propName} do nothing after the initial render.`,
  405. );
  406. }
  407. }
  408. }
  409. const RNCUIWebView = requireNativeComponent('RNCUIWebView');
  410. const RNCWKWebView = requireNativeComponent('RNCWKWebView');
  411. const styles = StyleSheet.create({
  412. container: {
  413. flex: 1,
  414. },
  415. errorContainer: {
  416. flex: 1,
  417. justifyContent: 'center',
  418. alignItems: 'center',
  419. backgroundColor: BGWASH,
  420. },
  421. errorText: {
  422. fontSize: 14,
  423. textAlign: 'center',
  424. marginBottom: 2,
  425. },
  426. errorTextTitle: {
  427. fontSize: 15,
  428. fontWeight: '500',
  429. marginBottom: 10,
  430. },
  431. hidden: {
  432. height: 0,
  433. flex: 0, // disable 'flex:1' when hiding a View
  434. },
  435. loadingView: {
  436. backgroundColor: BGWASH,
  437. flex: 1,
  438. justifyContent: 'center',
  439. alignItems: 'center',
  440. height: 100,
  441. },
  442. webView: {
  443. backgroundColor: '#ffffff',
  444. },
  445. });
  446. module.exports = WebView;