A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Detect browser close / page exit using Javascript

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`);
<body onUnload = " myUnloadEvent(); " >
Body of the page here.

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

This entry was posted in General and tagged , . Bookmark the permalink.

5 Responses to Detect browser close / page exit using Javascript

  1. sandrar says:

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

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

  3. Sanjeewa says:

    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?

  4. Wenbert says:

    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.

  5. parmod says:

    This work will be on every refresh of the page

    but i want to delete record from table
    just after the close button is triggeredor browser is closed

    anyone can help me

    thank”s in advance

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>