I need to clear the session variables when the tab is closed but I could not find any solutions so far. The closest I have got is by using the \"onbeforeunload\" function is
There is no secure way of handling what you are looking for. onbeforunload event executes every time you leave the page. (I had similar problem like this yesterday for one of my projects). The closest you can get is to control how the users leave the page.
See this link posted by lan in some of the comments. And check the answer by Daniel Melo That is as close you can get with the solution from this problem.
I also found this link but its basically the extraction of the answers given in stackoverflow.
Hope this helps.
Yep you can do it,
</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>
Unfortunately, there is no way to prevent page refresh (caused by form submit or any other navigation) from calling "onbeforeunload".