Back to Top

Detect browser tab refresh and browser tab close using javascript

Updated 11 June 2014

There is no function to differentiate between browser tab refresh and browser tab close but i found a way to differentiate between two.

We have

Function ‘onload’ – it is fired when we refresh browser tab.

Function ‘unload’ – it is fired when we either refresh browser tab or close browser tab.

Requirement

Start your headless eCommerce
now.
Find out More

We don’t have a single function in javascript which works only on browser tab close.

How to achieve this ?

Solution

var validNavigation = 0;

function endSession() 
{
   // Browser or Broswer tab is closed
   // Write code here
   alert('Browser or Broswer tab closed');
}

function bindDOMEvents() {
/*

* unload works on both closing tab and on refreshing tab.

*/
$(window).unload(function() 
{
   if (validNavigation==0) 
   {
     endSession();
   }
}

// Attach the event keypress to exclude the F5 refresh
$(document).keydown(function(e)
{
   var key=e.which || e.keyCode;
   if (key == 116)
   {
     validNavigation = 1;
   }
});

// Attach the event click for all links in the page
$("a").bind("click", function() 
{
   validNavigation = 1;
});

 // Attach the event submit for all forms in the page
 $("form").bind("submit", function() 
{
   validNavigation = 1;
});

 // Attach the event click for all inputs in the page
 $("input[type=submit]").bind("click", function() 
{
   validNavigation = 1;
});

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() 
{
   bindDOMEvents(); 
});

. . .

Leave a Comment

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


4 comments

  • Sagar Shinde
  • Sarath P Sasidharan
    • Webkul Support
  • blacmoon
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home