I have also been struggling with "unload" and "beforeunload" events to check for tab close but these function also fires up if the page refreshes using any Links or FORM submit in the document. So i found the following piece of code and it worked for me. It will prevent from firing up the "beforeunload" event on Anchor clicks and FORM submit.
The drawback of this code is that it still cannot differentiate if a user presses F5 or browser refresh button or back button. But i hope it helps you or any other person is some way. :)
//Message you wish to display upon closing tab window
var exitmessage = 'Are you sure you want to leave the site?';
//Load Event fires up on every body load
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
} func(); }
}
}
// Add a click event to a tag
function addClickEvent(a,i,func) {
if (typeof a[i].onclick != 'function') {
a[i].onclick = func;
}
}
theBody = document.body; if (!theBody) {
theBody = document.getElementById("body");
if (!theBody) {
theBody = document.getElementsByTagName("body")[0];
}
}
//Set a variable to prevent running the code on links visit or form submit
var PreventExit = false;
//The actual function that works on tab close or when the beforeunload function is fired
function DisplayExit(){
if(PreventExit == false){
PreventExit = true;
//run whatever code you want to run here. We are just displaying an alert message
return exitmessage;
}
}
//Search for A tags and prevent running the unload event
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
if(a[i].target !== '_blank') {
addClickEvent(a,i, function(){
PreventExit = true;
});
} else{
addClickEvent(a,i, function(){
PreventExit = false;
});
}
}
disablelinksfunc = function(){
var a = document.getElementsByTagName('A');
for (var i = 0; i < a.length; i++) {
if(a[i].target !== '_blank') {
addClickEvent(a,i, function(){
PreventExit = true; });
} else{
addClickEvent(a,i, function(){
PreventExit = false;
});
}
}
}
addLoadEvent(disablelinksfunc);
//Disable event to fire up on a FORM submit
disableformsfunc = function(){
var f = document.getElementsByTagName('FORM');
for (var i=0;i<f.length;i++){
if (!f[i].onclick){
f[i].onclick=function(){
PreventExit = true;
}
}else if (!f[i].onsubmit){
f[i].onsubmit=function(){
PreventExit = true;
}
}
}
}
addLoadEvent(disableformsfunc);
window.onbeforeunload = DisplayExit;