I want to destroy the session on tab close using jquery and java script. In this I am able to track the keyboard event like F5 or ctrl+r. But I am facing issues in tracking browser back, forward, refresh and tab close buttons.I know that on all the above mention button, same function is called that is window.onbeforeunload.
Here is my code..
function endSession() {
console.log(validNavigation);
alert("You are about to close your page and session");
$.ajax({
type: "POST",
url: base_url+"destroy-session",
beforeSend : function(){
console.log('hjkl');
},
success: function(response){
console.log(response);
},
error: function(response){
console.log(response);
}
});
}
function wireUpEvents() {
window.onbeforeunload = function() {
if (validNavigation == false) {
endSession();
}
}
//window.onbeforeunload=goodbye
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress keydown keyup', function(e) {
if(e.keyCode === 116 || e.keyCode==8 || e.keyCode==13) {
validNavigation = true;
}
if(e.ctrlKey && e.keyCode==82) {
validNavigation = true;
}
if(e.ctrlKey && e.keyCode==76) {
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;
});
$("input[type=button]").bind("click", 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();
});