No Description

WebViewShared.ts 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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 } from 'react-native';
  12. import {
  13. WebViewNavigationEvent,
  14. WebViewNavigation,
  15. } from './types/WebViewTypes';
  16. const defaultOriginWhitelist = ['http://*', 'https://*'];
  17. const extractOrigin = (url: string): string => {
  18. const result = /^[A-Za-z0-9]+:(\/\/)?[^/]*/.exec(url);
  19. return result === null ? '' : result[0];
  20. };
  21. const originWhitelistToRegex = (originWhitelist: string): string =>
  22. escapeStringRegexp(originWhitelist).replace(/\\\*/g, '.*');
  23. const passesWhitelist = (compiledWhitelist: Array<string>, url: string) => {
  24. const origin = extractOrigin(url);
  25. return compiledWhitelist.some(x => new RegExp(x).test(origin));
  26. };
  27. const compileWhitelist = (originWhitelist?: string[]): string[] =>
  28. ['about:blank', ...(originWhitelist || [])].map(originWhitelistToRegex);
  29. const createOnShouldStartLoadWithRequest = (
  30. loadRequest: (
  31. shouldStart: boolean,
  32. url: string,
  33. lockIdentifier?: number,
  34. ) => void,
  35. originWhitelist?: string[],
  36. onShouldStartLoadWithRequest?: (event: WebViewNavigation) => boolean,
  37. ) => ({ nativeEvent }: WebViewNavigationEvent) => {
  38. let shouldStart = true;
  39. const { url, lockIdentifier } = nativeEvent;
  40. if (!passesWhitelist(compileWhitelist(originWhitelist), url)) {
  41. Linking.openURL(url);
  42. shouldStart = false;
  43. }
  44. if (onShouldStartLoadWithRequest) {
  45. shouldStart = onShouldStartLoadWithRequest(nativeEvent);
  46. }
  47. loadRequest(shouldStart, url, lockIdentifier);
  48. };
  49. export {
  50. defaultOriginWhitelist,
  51. createOnShouldStartLoadWithRequest,
  52. originWhitelistToRegex,
  53. };