react-native-webview.git

WebView.ios.js 13KB

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