Executing a Script When Closing a Page

Window Events: onbeforeunload and onunload

These two events are non-standard events, although they are supported by all major browsers.

window.onbeforeunload = function() {
return "Can't you stay a little longer, dude?";
};
window.onunload = function() {
alert ("goodbye. onunload event");
};

You'll notice that in Firefox your custom message is not displayed.

It is not possible to use location.href in either of these events, but you can open a new window with window.open('mypage.html','windowName','params');