sanitize URL
清理网址
// A javascript: URL can contain leading C0 control or \u0020 SPACE,
// and any newline or tab are filtered out as if they're not part of the URL.
// 一个 javascript: URL 可以包含前导的 C0 控制字符或空格( ), 并且任何换行或制表符
// 都会被过滤掉,就好像它们不是 URL 的一部分。
// https://url.spec.whatwg.org/#url-parsing
// Tab or newline are defined as \r\n\t:
// 制表符或换行符定义为 :
// https://infra.spec.whatwg.org/#ascii-tab-or-newline
// A C0 control is a code point in the range \u0000 NULL to \u001F
// INFORMATION SEPARATOR ONE, inclusive:
// C0 控制字符是指范围从 NULL 到 INFORMATION SEPARATOR ONE(包括)的代码点:
// https://infra.spec.whatwg.org/#c0-control-or-space
// 是JavaScript协议
const isJavaScriptProtocol =
/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i;
function sanitizeURL<T>(url: T): T | string {
// We should never have symbols here because they get filtered out elsewhere.
// 我们这里绝不应该有符号,因为它们会在其他地方被过滤掉。
if (isJavaScriptProtocol.test('' + (url: any))) {
// Return a different javascript: url that doesn't cause any side-effects and just
// throws if ever visited.
// 返回一个不同的 javascript: URL,不会导致任何副作用,只会在访问时抛出异常。
return "javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')";
}
return url;
}
export default sanitizeURL;