JavaScript document.domain未捕获DOMException:阻止了具有来源的框架 [英] JavaScript document.domain Uncaught DOMException: Blocked a frame with origin
问题描述
我正在测试SOP时,我遇到这种情况,两个文档与我期望的域具有相同的关系,当我尝试获取位置时会引发错误。
While I was testing the SOP, i came to this scenario two documents has a relationship with the same domain as i would expected and it throws an error when i try to get the location.
要重现该问题:
- 打开 https://www.google.com
- 从控制台
打开= window.open( https://www.google.com)
- 从同一窗口执行
opened.location。 toString()
将从第二个选项卡的控制台返回正确的位置 - do
document.domain = www.google.com
-
在第一个选项卡中执行
opened.location.toString()
,您将获得错误
- Open https://www.google.com
- from the console
let opened = window.open("https://www.google.com")
- from the same window do
opened.location.toString()
which will return the correct location - from the second tab's console do
document.domain = "www.google.com"
from the first tab do
opened.location.toString()
and you will get an error
Uncaught DOMException: Blocked a frame with origin "https://www.google.com" from accessing a cross-origin frame.
at <anonymous>:1:12
有人可以解释这种奇怪的行为吗?
Can anyone explain this strange behavior?
推荐答案
此错误不是错误。同源策略是一种安全机制,可确保窗口对象仅有权访问他们被授权获取的信息。对于您而言,这包括可以访问 opened.location
。
This error is not a bug. The same-origin policy is a security mechanism that ensures that window objects only have access to the informations they are authorized to get. In your case, this includes having access to opened.location
.
创建后,两个标签的来源相同,这允许第一个访问 opened.location
。但是,在调用 document.domain ='www.google.com'
之后,它们不再存在。
Upon creation, both tabs have the same origin, which allows the first one to access opened.location
. But after the call to document.domain='www.google.com'
, they don't anymore.
什么?但是在两个选项卡中, window.location.origin
都是相同的
"What? But in both tabs, window.location.origin
are identical"
是的,但是有点复杂。来源由方案/主机/端口元组定义,有关更多详细信息,请参见@TheUnknown的答案。方案和主机始终保持不变,它们是 window.location.origin
字符串中包含的那个。
Yes, but it is a little bit more complex. The origin is defined by the scheme/host/port tuple, see @TheUnknown's answer for more details. The scheme and host stay the same all along, and they're the one included in the string of window.location.origin
.
要知道的棘手问题是,对 document.domain
的任何调用,包括 document.domain = document.domain
,导致端口号被 null
覆盖,从而导致两个选项卡的来源有所不同,并阻止了它们之间的通信诸如 opened.location
之类的信息相互之间,因此是错误。
The tricky thing to know is that any call to document.domain
, including document.domain = document.domain
, causes the port number to be overwritten with null
, therefore causing a difference in the two tabs' origins, and preventing them from communicating informations like opened.location
with one another, thus the error.
来自MDN的关于同源政策的指南
这篇关于JavaScript document.domain未捕获DOMException:阻止了具有来源的框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!