Detect browser close / page exit using Javascript

Posted on: Oct 05, 2007 by wenbert

Here is a sample code to detect that a browser is closed or a link has been clicked. This detects if the user is exiting the page. I am using this for locking/unlocking table rows in my database.

<script type="text/javascript">
function myUnloadEvent() {
    alert (`call ajax to update stuff`);
}
</script>
<body onUnload = " myUnloadEvent(); " >
Body of the page here.
</body>

The onUnload() event is responsible for the entire thing.


Subscribe to comments Comment | Trackback |
Post Tags: ,

Browse Timeline


Comments ( 4 )

Hi! I was surfing and found your blog post… nice! I love your blog. :) Cheers! Sandra. R.

sandrar added these pithy words on Sep 10 09 at 10:03 PM

I love your site. :) Love design!!! I just came across your blog and wanted to say that I

angelina jolie added these pithy words on Sep 11 09 at 12:18 AM

I want to display an alert when user closes the web browser. onLoad , onBeforeUnload are get triggered when user refresh the page or try to go to another page. What I really want to track is user closing the window by pressing (X) or Cntrl+W. I’m using JSF and XHTML and it’s a SEAM environment. Should work for FF and IE. Do you have any idea?

Sanjeewa added these pithy words on Nov 10 09 at 1:33 PM

Sanjeewa, the example above should work. It will call the myUnloadEvent() when the window/tab is closed. Either by clicking on the X-button or pressing CTRL+W. This should also work in IE and FF.

Wenbert added these pithy words on Nov 10 09 at 3:09 PM

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">


© Copyright 2007 eKini Web Developer Blog . Thanks for visiting!