Search code examples
javascriptdomsame-origin-policy

JavaScript document.domain Uncaught DOMException: Blocked a frame with origin


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.

To reproduce the problem:

  1. Open https://www.google.com
  2. from the console let opened = window.open("https://www.google.com")
  3. from the same window do opened.location.toString() which will return the correct location
  4. from the second tab's console do document.domain = "www.google.com"
  5. 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?


Solution

  • 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.

    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.

    "What? But in both tabs, window.location.origin are identical"

    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.

    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.

    Informations extracted from MDN's guide on same-origin policy