12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- /**
- * Copyright (c) 2015-present, Facebook, Inc.
- *
- * This source code is licensed under the MIT license found in the
- * LICENSE file in the root directory of this source tree.
- *
- * @format
- * @flow
- */
-
- import escapeStringRegexp from 'escape-string-regexp';
- import { Linking, UIManager as NotTypedUIManager } from 'react-native';
- import {
- WebViewNavigationEvent,
- OnShouldStartLoadWithRequest,
- CustomUIManager,
- } from './WebViewTypes';
-
- const UIManager = NotTypedUIManager as CustomUIManager;
-
- const defaultOriginWhitelist = ['http://*', 'https://*'];
-
- const extractOrigin = (url: string): string => {
- const result = /^[A-Za-z][A-Za-z0-9\+\-\.]+:(\/\/)?[^/]*/.exec(url);
- return result === null ? '' : result[0];
- };
-
- const originWhitelistToRegex = (originWhitelist: string): string =>
- `^${escapeStringRegexp(originWhitelist).replace(/\\\*/g, '.*')}`;
-
- const passesWhitelist = (compiledWhitelist: string[], url: string) => {
- const origin = extractOrigin(url);
- return compiledWhitelist.some(x => new RegExp(x).test(origin));
- };
-
- const compileWhitelist = (originWhitelist: string[]): string[] =>
- ['about:blank', ...(originWhitelist || [])].map(originWhitelistToRegex);
-
- const createOnShouldStartLoadWithRequest = (
- loadRequest: (
- shouldStart: boolean,
- url: string,
- lockIdentifier: number,
- ) => void,
- originWhitelist: string[],
- onShouldStartLoadWithRequest?: OnShouldStartLoadWithRequest,
- ) => {
- return ({ nativeEvent }: WebViewNavigationEvent) => {
- let shouldStart = true;
- const { url, lockIdentifier } = nativeEvent;
-
- if (!passesWhitelist(compileWhitelist(originWhitelist), url)) {
- Linking.openURL(url);
- shouldStart = false;
- }
-
- if (onShouldStartLoadWithRequest) {
- shouldStart = onShouldStartLoadWithRequest(nativeEvent);
- }
-
- loadRequest(shouldStart, url, lockIdentifier);
- };
- };
-
- const getViewManagerConfig = (
- viewManagerName: 'RNCUIWebView' | 'RNCWKWebView' | 'RNCWebView',
- ) => {
- if (!UIManager.getViewManagerConfig) {
- return UIManager[viewManagerName];
- }
- return UIManager.getViewManagerConfig(viewManagerName);
- };
-
- export {
- defaultOriginWhitelist,
- createOnShouldStartLoadWithRequest,
- getViewManagerConfig,
- };
|