While a pure javascript redirect function would be a better solution most of the time, there might be times that you need it.
Take a look at these:
http://www.w3schools.com/jsref/event_onunload.asp
Alerts when navigating away from a web page
http://msdn.microsoft.com/en-us/library/ie/ms536907(v=vs.85).aspx
https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
Basically, an event is fired when the user tries to close or navigate away from the page. You can hook up to that event for customization.
window.onbeforeunload = function () {
var who = ["lover", "friend"][(Math.floor(Math.random()*2)+1)];
return "Goodbye my " + who;
};
This function is supposed to return a string or nothing. If it is a string, a dialog box appears for confirmation of navigating away; if it is nothing, i.e. undefined, no interception happens.
Also n ote that:
Since 25 May 2011, the HTML5 specification states that calls to window.showModalDialog(), window.alert(), window.confirm() and window.prompt() methods may be ignored during this event.