説明なし

WebViewShared.js 1.9KB

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