gpt4 book ai didi

javascript 如何检查 URL 是否与当前页面同源?

转载 作者:行者123 更新时间:2023-12-05 08:43:17 25 4
gpt4 key购买 nike

如何检查特定 URL 字符串是否与当前页面来自同一来源/主机?例如,如果我想绑定(bind)到链接,但只防止默认链接到同一主机...

最佳答案

来自 RFC 6454 的 Origin 定义:

Roughly speaking, two URIs are part of the same origin (i.e., represent the same principal) if they have the same scheme, host, and port.

因此我们需要比较两个URI中的scheme、host和port,如果相同,则这两个URI同源。

一个有效的代码片段:

function isOriginSameAsLocation(url) {
var pageLocation = window.location;
var URL_HOST_PATTERN = /(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/;
var urlMatch = URL_HOST_PATTERN.exec(url) || [];
var urlparts = {
protocol: urlMatch[1] || '',
host: urlMatch[2] || '',
port: urlMatch[3] || ''
};

function defaultPort(protocol) {
return {'http:':80, 'https:':443}[protocol];
}

function portOf(location) {
return location.port || defaultPort(location.protocol||pageLocation.protocol);
}

return !!( (urlparts.protocol && (urlparts.protocol == pageLocation.protocol)) &&
(urlparts.host && (urlparts.host == pageLocation.host)) &&
(urlparts.host && (portOf(urlparts) == portOf(pageLocation)))
);
}

关于javascript 如何检查 URL 是否与当前页面同源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31374766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com