document.domain 的 Chrome 解决方案

Posted

技术标签:

【中文标题】document.domain 的 Chrome 解决方案【英文标题】:Chrome solution for document.domain 【发布时间】:2011-10-29 12:13:42 【问题描述】:

由于某种原因,chrome 不再支持 document.domain 并且当在包含子域的 iframe 和包含 iframe 的子域中读取该行时会吐出错误。反正有这个吗?

错误:未捕获的错误:SECURITY_ERR:DOM 异常 18

【问题讨论】:

【参考方案1】:

文档域应为小写,规则如下:

// Actual domain is "www.foo.com" 
document.domain = "foo.com"; // this is valid 

// Actual domain is "bar.foo.com" 
document.domain = "www.foo.com"; // this is invalid, "bar.foo.com" is not a subdomain of "www.foo.com" 

// Actual domain is "blah.bar.foo.com" 
document.domain = "bar.foo.com" // Ok 
document.domain = "foo.com" // Still ok 
document.domain = "bar.foo.com" // Invalid, you can't change it back to a more specific domain. 

【讨论】:

以防万一有人在寻找参考:developer.mozilla.org/en-US/docs/Web/Security/…【参考方案2】:

document.domain 应该适用于 iframe,只要您在同一个域中:

iframe=document.querySelector('iframe');
console.log(iframe.contentDocument.domain)

如果您尝试访问与父框架位于不同域中的 iframe 的文档,则会收到您所看到的安全错误。

请注意,子域也被视为不同的域,因此您会遇到跨域问题:A question about cross-domain (subdomain) ajax request

【讨论】:

以上是关于document.domain 的 Chrome 解决方案的主要内容,如果未能解决你的问题,请参考以下文章

Chrome 又搞事情,这种跨域方案要被禁用了!

即使正确设置了 document.domain,跨子域 ajax 请求也会被拒绝

document.domain = document.domain 有啥作用?

document.domain = document.domain 有啥作用?

搞事情,这种跨域方案快要被禁用了!

document.domain