- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在实际尝试使用 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/
我的 coinbase 支付按钮不会显示。我从 coinbase 收到此错误消息: 拒绝显示' https://coinbase.com/transactions ' 在框架中,因为它将 'X-Fra
我有一个 Web 应用程序,它作为托管在单个父窗口中的多个 iframe 运行(基本上是修改后的 GWT)http://en.wikipedia.org/wiki/Google_Web_Toolkit
CORS 表示: A web application executes a cross-origin HTTP request when it requests a resource that has
假设我有一个 CPU 密集型 iframe。 它与父页面在同一个域中,因此不适用跨域,因此它共享父页面的事件循环。 是否可以为 iframe 提供一个单独的 JS 上下文(包括一个单独的事件循环),这
我是一名优秀的程序员,十分优秀!