react-native-webview.git

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