3

I have one problem, I have a javascript function which I want to use when the browser is closed, How can I detect that a browser is being closed?

I have made some research on that I got solution like onunload or beforeunload but both the functions are being executed when I am reloading the page, Is there any solution that I can differentiate reload and browser/tab close.

gdoron
  • 147,333
  • 58
  • 291
  • 367
Rohitashv Singhal
  • 4,517
  • 13
  • 57
  • 105

3 Answers3

4

No, you can't know that, the HTML page isn't the "owner" of the browser, you have only limited access to information, and this info isn't inside it.

You can know when the user leaves your page, but you can't know why, as it's none of your business...

gdoron
  • 147,333
  • 58
  • 291
  • 367
2

gdoron is correct in that you cannot determine why/how the user is 'leaving the page'. On the extremes you can perhaps determine on mousedown events if the browser's CLOSE button was clicked and let that fire of an alert. But this would probably require tracking the X and Y of the mousedown event and that isn't a very nice way of doing things. And i do not think you would be able to accurately determine if a tab is closed.

David 'the bald ginger'
  • 1,296
  • 3
  • 20
  • 38
1

answer is,

</head>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {
     endSession();
  }
 }

// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
  validNavigation = true;
}
});

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

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

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

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();  
}); 
</script>    
</head>
<body>
<h1>Eureka!</h1>
  <a href="http://www.google.com">Google</a>
  <a href="http://www.yahoo.com">Yahoo</a>
</body>
</html>
Yatin Trivedi
  • 661
  • 6
  • 9
  • 6
    What if user refresh the browser tab by clicking on refresh icon? – Vardan Jun 24 '14 at 13:06
  • 1
    Doesn't actually solve the original question because it won't differentiate between close and reload window, although a valiant effort. – macguru2000 Oct 13 '14 at 18:02