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 –
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(); });
4 comments