如何更改当前文档的域?
我在来自不同域的 document
中有一个 iframe
。由于这个原因,浏览器似乎阻止我访问内部 iframe。我可以将两个域更改为相同的值吗?我尝试了 document.domain = 'targetdomain'
,但是抛出了 DOM 异常。
I have an iframe
in a document
from a different domain. It seems the browser blocks me to access the inner iframe for this reason. Can I change both domain to the same value? I tried document.domain = 'targetdomain'
, but there is DOM exception thrown out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
iframe 的域是加载到 iframe 中的 URL 的域。
如果您愿意在不同的域上,您可以将
iframe.src
更改为不同的文档,但您无法在保持加载相同文档的同时更改 iframe 本身的域,以便能够访问内容,因为这正是同源策略所保护的安全违规行为。更改域的一个例外是使用子域时。您可以在此处了解相关内容。
因此,除非这两个域之一是另一个域的子域,否则您无法从另一个域访问其中一个域。
在最新的浏览器中,有一个 HTML5 消息传递方案,允许来自不同域的两个协作框架/窗口相互交换消息。这里的关键是两个框架/窗口必须合作才能实现这一点(这意味着您必须对两个框架/窗口都有代码控制)。您可以在此处了解更多相关信息。
The domain of the iframe is the domain of the URL that loaded into the iframe.
You can change the
iframe.src
to a different document if you like on a different domain, but you cannot change the domain of the iframe itself while keeping the same document loaded in order to enable you to access the content as that would be the very security violation that the same-origin policy protects from.The one exception to changing the domain is when using sub-domains. You can read about that here.
So, unless one of these two domains is a sub-domain of the other, you cannot access one from the other.
In the latest browsers, there is an HTML5 message passing scheme that allows two cooperating frames/windows from different domains to exchange messages with each other. The key here is that both frames/windows must cooperate for this to happen (meaning you must have code control over both frames/windows). You can read more about that here.