javascript - 与 document.domain 和 CORS 相关的这种不一致行为的解释是什么?

标签 javascript cors

在使用 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/

相关文章:

javascript - 无法使用 jQuery 删除或添加类

javascript - 使用 meteor 方法但仍然出现错误

javascript - Chrome 扩展程序 20 小时后没有 'Access-Control-Allow-Origin' header

javascript - 以 Angular 向谷歌表单提交数据时出现 CORS 问题

javascript - 简单的 Javascript 计算器,出了问题吗?

javascript - 默认路由总是在 react 路由器中执行

javascript - Webpack url-loader 内联 jpg 文件

javascript - 从 Rails 设置 document.domain 的 DRY 方式

c# - 带有自定义 header 的 Ajax 请求发送到启用了 CORS 的 Web API 服务器

javascript - Firebase Cloud Functions https.onCall 已完成,状态代码为 : 204