Nav apraksta

WebView.ios.tsx 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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;
  58. };
  59. const defaultRenderLoading = () => (
  60. <View style={styles.loadingView}>
  61. <ActivityIndicator />
  62. </View>
  63. );
  64. const defaultRenderError = (
  65. errorDomain: string,
  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. {...nativeConfig.props}
  253. />
  254. );
  255. return (
  256. <View style={styles.container}>
  257. {webView}
  258. {otherView}
  259. </View>
  260. );
  261. }
  262. _getCommands() {
  263. if (!this.props.useWebKit) {
  264. return UIManager.RNCUIWebView.Commands;
  265. }
  266. return UIManager.RNCWKWebView.Commands;
  267. }
  268. /**
  269. * Go forward one page in the web view's history.
  270. */
  271. goForward = () => {
  272. UIManager.dispatchViewManagerCommand(
  273. this.getWebViewHandle(),
  274. this._getCommands().goForward,
  275. null
  276. );
  277. };
  278. /**
  279. * Go back one page in the web view's history.
  280. */
  281. goBack = () => {
  282. UIManager.dispatchViewManagerCommand(
  283. this.getWebViewHandle(),
  284. this._getCommands().goBack,
  285. null
  286. );
  287. };
  288. /**
  289. * Reloads the current page.
  290. */
  291. reload = () => {
  292. this.setState({ viewState: WebViewState.LOADING });
  293. UIManager.dispatchViewManagerCommand(
  294. this.getWebViewHandle(),
  295. this._getCommands().reload,
  296. null
  297. );
  298. };
  299. /**
  300. * Stop loading the current page.
  301. */
  302. stopLoading = () => {
  303. UIManager.dispatchViewManagerCommand(
  304. this.getWebViewHandle(),
  305. this._getCommands().stopLoading,
  306. null
  307. );
  308. };
  309. /**
  310. * Posts a message to the web view, which will emit a `message` event.
  311. * Accepts one argument, `data`, which must be a string.
  312. *
  313. * In your webview, you'll need to something like the following.
  314. *
  315. * ```js
  316. * document.addEventListener('message', e => { document.title = e.data; });
  317. * ```
  318. */
  319. postMessage = (data: string) => {
  320. UIManager.dispatchViewManagerCommand(
  321. this.getWebViewHandle(),
  322. this._getCommands().postMessage,
  323. [String(data)]
  324. );
  325. };
  326. /**
  327. * Injects a javascript string into the referenced WebView. Deliberately does not
  328. * return a response because using eval() to return a response breaks this method
  329. * on pages with a Content Security Policy that disallows eval(). If you need that
  330. * functionality, look into postMessage/onMessage.
  331. */
  332. injectJavaScript = (data: string) => {
  333. UIManager.dispatchViewManagerCommand(
  334. this.getWebViewHandle(),
  335. this._getCommands().injectJavaScript,
  336. [data]
  337. );
  338. };
  339. /**
  340. * We return an event with a bunch of fields including:
  341. * url, title, loading, canGoBack, canGoForward
  342. */
  343. _updateNavigationState = (event: WebViewNavigationEvent) => {
  344. if (this.props.onNavigationStateChange) {
  345. this.props.onNavigationStateChange(event.nativeEvent);
  346. }
  347. };
  348. /**
  349. * Returns the native `WebView` node.
  350. */
  351. getWebViewHandle = () => {
  352. return findNodeHandle(this.webViewRef.current);
  353. };
  354. _onLoadingStart = (event: WebViewNavigationEvent) => {
  355. const onLoadStart = this.props.onLoadStart;
  356. onLoadStart && onLoadStart(event);
  357. this._updateNavigationState(event);
  358. };
  359. _onLoadingError = (event: WebViewErrorEvent) => {
  360. event.persist(); // persist this event because we need to store it
  361. const { onError, onLoadEnd } = this.props;
  362. onError && onError(event);
  363. onLoadEnd && onLoadEnd(event);
  364. console.warn("Encountered an error loading page", event.nativeEvent);
  365. this.setState({
  366. lastErrorEvent: event.nativeEvent,
  367. viewState: WebViewState.ERROR
  368. });
  369. };
  370. _onLoadingFinish = (event: WebViewNavigationEvent) => {
  371. const { onLoad, onLoadEnd } = this.props;
  372. onLoad && onLoad(event);
  373. onLoadEnd && onLoadEnd(event);
  374. this.setState({
  375. viewState: WebViewState.IDLE
  376. });
  377. this._updateNavigationState(event);
  378. };
  379. _onMessage = (event: WebViewMessageEvent) => {
  380. const { onMessage } = this.props;
  381. onMessage && onMessage(event);
  382. };
  383. _onLoadingProgress = (event: NativeSyntheticEvent<WebViewProgressEvent>) => {
  384. const { onLoadProgress } = this.props;
  385. onLoadProgress && onLoadProgress(event);
  386. };
  387. componentDidUpdate(prevProps: WebViewSharedProps) {
  388. if (!(prevProps.useWebKit && this.props.useWebKit)) {
  389. return;
  390. }
  391. this._showRedboxOnPropChanges(prevProps, "allowsInlineMediaPlayback");
  392. this._showRedboxOnPropChanges(prevProps, "mediaPlaybackRequiresUserAction");
  393. this._showRedboxOnPropChanges(prevProps, "dataDetectorTypes");
  394. if (this.props.scalesPageToFit !== undefined) {
  395. console.warn(
  396. "The scalesPageToFit property is not supported when useWebKit = true"
  397. );
  398. }
  399. }
  400. _showRedboxOnPropChanges(
  401. prevProps: WebViewSharedProps,
  402. propName:
  403. | "allowsInlineMediaPlayback"
  404. | "mediaPlaybackRequiresUserAction"
  405. | "dataDetectorTypes"
  406. ) {
  407. if (this.props[propName] !== prevProps[propName]) {
  408. console.error(
  409. `Changes to property ${propName} do nothing after the initial render.`
  410. );
  411. }
  412. }
  413. }
  414. const RNCUIWebView = requireNativeComponent("RNCUIWebView");
  415. const RNCWKWebView = requireNativeComponent("RNCWKWebView");
  416. const styles = StyleSheet.create({
  417. container: {
  418. flex: 1
  419. },
  420. errorContainer: {
  421. flex: 1,
  422. justifyContent: "center",
  423. alignItems: "center",
  424. backgroundColor: BGWASH
  425. },
  426. errorText: {
  427. fontSize: 14,
  428. textAlign: "center",
  429. marginBottom: 2
  430. },
  431. errorTextTitle: {
  432. fontSize: 15,
  433. fontWeight: "500",
  434. marginBottom: 10
  435. },
  436. hidden: {
  437. height: 0,
  438. flex: 0 // disable 'flex:1' when hiding a View
  439. },
  440. loadingView: {
  441. backgroundColor: BGWASH,
  442. flex: 1,
  443. justifyContent: "center",
  444. alignItems: "center",
  445. height: 100
  446. },
  447. webView: {
  448. backgroundColor: "#ffffff"
  449. }
  450. });