Free Android CakePHP GMaps Articles by Bali Web Design

July 21, 2010

How to handle user closing browser windows or page using javascript

Filed under: html,javascript — admin @ 12:40 am

Sometime we need to handle or do something when user closing a browser windows or page. Maybe we want to ask user if they really want to close the page or it was a mistake click. This procedure all can be done using javascript.

There are two condition or event that you can intercept before it really happen, first when user close the browser windows and second is when browser windows will be closed without any way to abort it.

For first condition we can handle it using window.onbeforeunload event.

function closeHandler() {
return “Are you sure you want to close this page?”;

window.onbeforeunload = closeHandler;

And second condition when window will really closed, you can put on body tag or using window object

<body onUnload=”doUnload()”>

<script language=”Javascript”>
function doUnload() {
// do your code here

or using window object

function doUnload() {
// do your code here
window.onunload = doUnload;

I hope this article is help you on handling user when closing browser windows or page using javascript.

1 Comment »

  1. it seems happen not only closing browser, but also refresh (F5)

    Comment by besso — September 1, 2010 @ 12:58 am

RSS feed for comments on this post. TrackBack URL

Leave a comment