在使用 document.domain
允许 CORS 时,似乎与访问限制略有不一致。即,将文档域从 A 更改为 B 继续允许对 A 的跨源请求,但不允许允许访问属于 A 的 iframe。
考虑以下示例:
<!-- b.html -->
<html>
<head>
</head>
</html>
<!-- test.domain.com/a.html -->
<html>
<head>
<script>
window.onload = function(e) {
document.domain = "domain.com";
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.onload = function(e) {
// This produces an access-denied error
console.log(iframe.contentWindow.location.href);
};
$.ajax({url: "test.domain.com/b.html", success: function(result){
console.log(result); // Will dump all of b.html
}});
};
</script>
</head>
</html>
我觉得这种情况很奇怪。一旦 document.domain
发生变化,对包含 b.html
的 iframe 的访问将受到限制,但对同一文档的 ajax 调用则不受限制。这种不一致是有原因的吗?也就是说,为什么浏览器在访问子框架时只考虑 document.domain
,即使浏览器“知道”子框架和父框架都来自同一来源?
最佳答案
document.domain
根据 HTML 标准影响源的 domain
部分:https://html.spec.whatwg.org/multipage/browsers.html#dom-document-domain .
然后,一些操作使用“同源”比较,一些操作使用“同源域”比较。参见 https://html.spec.whatwg.org/multipage/browsers.html#same-origin .
后者仅用于某些遗留场景,因为如今 document.domain
是网络中相当不需要的部分。因此,您会发现这些小的不一致。
关于javascript - 与 document.domain 和 CORS 相关的这种不一致行为的解释是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37048440/