mirror of
https://github.com/expo/react-native-webview.git
synced 2026-11-15 09:18:06 -10:00
Rewrote the whole repository into typescript. This will provide way better and up to date documentation. This should also add some safety for people contributing 😄 . Flow types were not working until now which is why this PR doesn't have them but feel free to PR. This also fixes #384 #435 #206 #171 #168.
74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
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: ReadonlyArray<string>,
|
|
url: string,
|
|
) => {
|
|
const origin = extractOrigin(url);
|
|
return compiledWhitelist.some(x => new RegExp(x).test(origin));
|
|
};
|
|
|
|
const compileWhitelist = (
|
|
originWhitelist: ReadonlyArray<string>,
|
|
): ReadonlyArray<string> =>
|
|
['about:blank', ...(originWhitelist || [])].map(originWhitelistToRegex);
|
|
|
|
const createOnShouldStartLoadWithRequest = (
|
|
loadRequest: (
|
|
shouldStart: boolean,
|
|
url: string,
|
|
lockIdentifier: number,
|
|
) => void,
|
|
originWhitelist: ReadonlyArray<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,
|
|
};
|