Capture the close event of popup window in JavaScript

While the accepted answer is correct for same origins I found a solution for cross origin popups:

var win = window.open('http://www.google.com'); 
var timer = setInterval(function() { 
    if(win.closed) {
        clearInterval(timer);
        alert('closed');
    }
}, 1000);

Source: atashbahar.com

For those considering using it.

Even Facebook is using this "hack" in their Javascript SDK.

You can verify this by having a look at their code. Just search for .closed in https://connect.facebook.net/en_US/sdk.js.


The event name is onbeforeunload and not onBeforeUnload. JS is case sensitive.


Your example will work as long as the pop-up window url is in the same domain as the parent page, and you change the event to all lowercase:

var new_window = window.open('some url')
new_window.onbeforeunload = function(){ /* my code */ }