Wednesday, June 27, 2007

Detect Window Close Event

Need to detect when the client is about to leave the site.

The <body> tag fires an event onbeforeunload when a page is refreshed or unloaded in the browser window. This event can somehow prevent the user from navigating away from the page or closing the window.

An event listener can also be attached to the window object that can do some AJAX processing or cleanup because it cannot prevent the browser window from closing.

Example:

<script type="text/javascript">

// event below works both in IE6,7 and Firefox
window.onunload = function()
{
// do processing here
alert('bye!');
}

function showUnloading(evt){
//IE specific code to cancel the navigation
//if you put a text value in that property IE will try to confirm
//if you want to navigate off the page.
//The code also works with Firefox
evt.returnValue = "You are leaving.";

//Firefox GeckoDOM specific
//below is how to handle the cancelling of firefox
if (!confirm('Are you sure?'))
{
evt.preventDefault;
evt.stopPropagation; // this makes sure it does not bubble up
}

}
</script>

<body onbeforeunload="showUnloading(event); >
</body>


There are lot of uses for the web application that detects the unloading of the body. It will be application specific on how you handle the event. There are a thousand way a user can navigate away from a web page and as always never trust that those events are guaranteed to fire.