Ingen beskrivning

WebViewShared.ts 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 escapeStringRegexp from 'escape-string-regexp';
  11. import { Linking, UIManager as NotTypedUIManager } from 'react-native';
  12. import {
  13. WebViewNavigationEvent,
  14. OnShouldStartLoadWithRequest,
  15. CustomUIManager,
  16. } from './WebViewTypes';
  17. const UIManager = NotTypedUIManager as CustomUIManager;
  18. const defaultOriginWhitelist = ['http://*', 'https://*'];
  19. const extractOrigin = (url: string): string => {
  20. const result = /^[A-Za-z][A-Za-z0-9\+\-\.]+:(\/\/)?[^/]*/.exec(url);
  21. return result === null ? '' : result[0];
  22. };
  23. const originWhitelistToRegex = (originWhitelist: string): string =>
  24. `^${escapeStringRegexp(originWhitelist).replace(/\\\*/g, '.*')}`;
  25. const passesWhitelist = (compiledWhitelist: string[], url: string) => {
  26. const origin = extractOrigin(url);
  27. return compiledWhitelist.some(x => new RegExp(x).test(origin));
  28. };
  29. const compileWhitelist = (originWhitelist: string[]): string[] =>
  30. ['about:blank', ...(originWhitelist || [])].map(originWhitelistToRegex);
  31. const createOnShouldStartLoadWithRequest = (
  32. loadRequest: (
  33. shouldStart: boolean,
  34. url: string,
  35. lockIdentifier: number,
  36. ) => void,
  37. originWhitelist: string[],
  38. onShouldStartLoadWithRequest?: OnShouldStartLoadWithRequest,
  39. ) => {
  40. return ({ nativeEvent }: WebViewNavigationEvent) => {
  41. let shouldStart = true;
  42. const { url, lockIdentifier } = nativeEvent;
  43. if (!passesWhitelist(compileWhitelist(originWhitelist), url)) {
  44. Linking.openURL(url);
  45. shouldStart = false;
  46. }
  47. if (onShouldStartLoadWithRequest) {
  48. shouldStart = onShouldStartLoadWithRequest(nativeEvent);
  49. }
  50. loadRequest(shouldStart, url, lockIdentifier);
  51. };
  52. };
  53. const getViewManagerConfig = (
  54. viewManagerName: 'RNCUIWebView' | 'RNCWKWebView' | 'RNCWebView',
  55. ) => {
  56. if (!UIManager.getViewManagerConfig) {
  57. return UIManager[viewManagerName];
  58. }
  59. return UIManager.getViewManagerConfig(viewManagerName);
  60. };
  61. export {
  62. defaultOriginWhitelist,
  63. createOnShouldStartLoadWithRequest,
  64. getViewManagerConfig,
  65. };