Code Simplified – Viral Sarvaiya

Code Simplified – Viral Sarvaiya, Web Developer Friends, dot net Developer, Sql Server Developer

Window Close Event of Browser

Posted by Viral Sarvaiya on April 12, 2011


recently i get a problem that what if some user accessing my website and close directly browser without logout from the system?

i get good solution with this but this is not 100% secure.

for that we have 2 events in javascript “onbeforeunload” or “onunload”

but onunload event is not working in firefox and some time in IE8 also, so onbeforeunload is suitable for both.

<title>Window Close Event of Browser</title>
<script language="javascript" type="text/javascript">
 function CloseBrowser() {
 alert("Browser is closing");

<body onbeforeunload="CloseBrowser();">



window.onbeforeunload = function() {
    return "Are you sure you want to leave this page bla bla bla?"; // you can make this dynamic, ofcourse...

As we have already discussed that there is no 100% fool proof way to detect the browser close event in a lot of cases, the above technique can fail. For example if the user kills the browser’s process from task manager, there could be many more cases. Yet in a lot of cases, this technique can be handy.

Best of luck and happy programming.

Thank you.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: