Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-domain window.close event from parent window

For example I'm on domain1:

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

Now I'm on domain2 and I'm closing it. How will window.win know that user closed that window? Is there any event or property to check via interval?

like image 541
Somebody Avatar asked Dec 16 '22 02:12

Somebody


1 Answers

There is a property which is not part of any W3C spec. It's called closed and would get accessed like

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

I'm not sure about the cross-browser compatibilty for that property. I'm also not sure how this behaves on cross-origin domains. But if you try it please let me and the rest of this community know about it.


Another option is that you take care for the notification yourself. That means, you are listening for the onbeforeunload within the popup-window. When the event fires, you could use HTML5's postMessage method to communicate between cross-domain windows. For instance:

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 on this solution is that it's only compatible with browser that support basic HTML5. There are other (sneaky) ways to have a cross-domain communication on old'ish browsers, but I guess that is another story.

like image 118
jAndy Avatar answered Dec 28 '22 06:12

jAndy