Javascript: cross-domain window window.close from parent window

For example, I am on domain 1:

a.click(function(){
  window.win=window.open(domain2,'name');
});

      

Now I am on domain2 and I am closing it. How does window.win know when the user has closed that window? Is there any event or property to check at intervals?

+3


source to share


3 answers


There is a property that is not part of the W3C specification. It was called closed

and would be accessed, for example

if( window.win.closed ) {
    // window was closed
}

      

I'm not sure about cross-browser compatibility for this property. I also don't know how this happens in cross-origin domains. But if you try, please let me and the rest of this community know about it.


Another option is that you take care of this notification yourself. This means that you are listening onbeforeunload

in a pop-up window. When the event fires, you can use HTML5 method postMessage

to communicate between cross-domain windows. For example:



MainWindow:

window.addEventListener('message', function(e) {
    if( e.origin === 'http://www.popupdomain.com' ) {
        if( e.data === 'closed' ) {
            alert('popup window was closed');
        }
    }
}, false);

      

Domain2:

window.onbeforeunload = function() {
    window.opener.postMessage('closed', 'http://www.popupdomain.com');
};

      

The only caveat with this solution is that it is only compatible with a browser that supports basic HTML5. There are other (hidden) ways to have cross-domain communication in older browsers, but I guess that's another story.

+5


source


You can check if the cross domain has been closed by using the closed window spacing check.



var url = "http://stackoverflow.com";
var width = 500;
var height = 500;
var closeCheckInterval = 500; //Check every 500 ms.

var popup =  window.open(url, "_new", 'width=' + width + ', height=' + height);
popup.focus();

var closeCheck = setInterval(function () {
    try {
        (popup == null || popup.closed) && (clearInterval(closeCheck), onWindowClosed());    
    } catch (ex) { }
}, closeCheckInterval);

var onWindowClosed = function () {
    ...
    // Stuff to do after window has closed
    ...
}

      

+1


source


I was working on a similar issue where domain1 window opens from domain2. I needed to check when the window is closed. I tried: -

  • I used window.onunload event, it didn't work due to Same origin policy and showed the following error

    Error: Attempting to execute compile-and-go script command in cleaned area Source file: chrome: //firebug/content/net/httpLib.js

    Error: Attempting to execute compile-and-go script command in cleaned area Source file: chrome: //firebug/content/firefox/tabWatcher.js

  • But I kept an array of Window objects and applied the "Window.closed" property , works even on cross domain. :)

  • Also you can try postMessage API or CORS

0


source







All Articles