gpt4 book ai didi

javascript - 检查同源政策是否适用

转载 作者:行者123 更新时间:2023-12-03 21:39:12 24 4
gpt4 key购买 nike

在实际尝试使用 ajax 方法之前,是否有一种“安全”的方法来检查同源策略是否适用于 URL?这是我所拥有的:

function testSameOrigin(url) {

var loc = window.location,
a = document.createElement('a');

a.href = url;

return a.hostname == loc.hostname &&
a.port == loc.port &&
a.protocol == loc.protocol;
}

这种方法可行,但它是一种基于 wikipedia article 的手动猜测。 。有没有更好的方法来预先检查跨域津贴? jQuery 可以使用。

最佳答案

Is there a "safe" way to check if the same origin policy applies to an URL before actually trying to use ajax methods? Here is what I have:

function testSameOrigin(url) {

var loc = window.location,
a = document.createElement('a');

a.href = url;

return a.hostname == loc.hostname &&
a.port == loc.port &&
a.protocol == loc.protocol;
}

如果您正在做(或者不做)某些事情,这是一种安全可靠的方法。

This sort of works, but it’s kind of a manual guess based on the wikipedia article.

这应该在“正常”情况下完全有效。如果您打算使用cross-domain scripting,则需要对其进行修改.

如果您在脚本中修改 document.domain,例如从“foo.example.com”和“bar.example.com”修改为“example.com”,则您的 testSameOrigin 函数对于“http://example.com ”将返回 false,而实际上它应该返回 true

如果您计划修改 document.domain,您只需在脚本中添加一个检查即可。

如果您计划使用 CORS(请参阅上面的链接)来允许跨域通信,它也会返回误报。但是,如果您使用 CORS,您将拥有一个可以与之通信的域列表,并且您也可以将该列表添加到此函数中。

Is there a better way of pre-checking cross domain allowance? jQuery is OK to use.

可能不是,尽管可能值得一提的是,您在史蒂夫的回答中在控制台中看到的可能是“观察者的困境”......这些错误看起来像是控制台试图检查另一个窗口造成的,不一定来自剧本。

假设您没有搞乱 document.domain 或使用 CORS,您原来的解决方案可能会更好,因为它不需要发出额外的请求来确定服务器是否可用或不是。即使您正在执行一些跨域脚本编写,修改现有的函数以适应它可能是您最好的选择。

关于javascript - 检查同源政策是否适用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9404793/

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