javascriptjquerysame-origin-policydomexception

Getting cross-origin frame exception for urls in the same domain, one url opened through callback from a third party website


I am trying to close this page and refresh the parent page using the code:

window.opener.windowClosing();
self.close();

I'm getting this error:

Uncaught DOMException: Blocked a frame with origin "aaa.bbb.com" from accessing a cross-origin frame. at aaa.bbb.com/xxx

It's happening even though both urls are in the same domain. I tried to check the domain using "document.domain", and I'm getting the following domain names:

aaa.bbb.com - bbb.com

aaa.bbb.com/xxx - aaa.bbb.com

In this case the aaa.bbb.com/xxx is a callback url that was called from a third party integration to provide the code for authorization. This callback url is showing the sub-domain but the parent page isn't showing that.

I thought the url being called from third party website might have been the issue. But then I used window.open to open this callback url, and I'm getting the same document.domain value and the same exception when closing it.


Solution

  • You can try explicitly setting document.domain on both pages so that they match.

    document.domain = 'aaa.bbb.com';
    

    Or you could use window.postMessage()

    Parent Document:

    window.addEventListener("message", receiveMessage, false);
    
    function receiveMessage(event) {
      if (event.origin.indexOf('bbb.com') < 0 {
        return;
      } else if (event.data == 'closing'){
        windowClosing()
      }
    }
    

    Child Document:

    window.opener.postMessage('closing', '*');
    self.close();
    

    If the child window is actually a frame or iframe, instead of a separate window, then you would use:

    window.parent.postMessage('closing', '*');
    self.close();
    

    In either case, you need to make sure that the protocol (http/https) and port are the same for both windows/frames as well.