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.
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 */ }
The event name is onbeforeunload
and not onBeforeUnload
. JS is case sensitive.
You need to bind the onbeforeunload
event to the window AFTER it is opened.
The simplest way to do that would be to have the javascript onbeforeunload code within the window source code.
For detailed explanations, refer to these two very similar questions here and here on Stackoverflow.