Açıklama Yok

WebView.ios.tsx 14KB

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