0

I want to detect browser/tab close event. I have tried "beforeunload", "unload" etc on both in jQuery and Javascript. The solutions working on tab/browser close as well as when reload page.

Is it possible in jQuery/Javascript to detect Tab/Browser close event? which will not fire in reload.

some of the followings working on both in reload and tab/browser close

var inFormOrLink;

$(window).bind("beforeunload", function () {
    return inFormOrLink ? "Do you really want to close?" : null;
});

and

window.addEventListener("beforeunload", function (e) {
    var confirmationMessage = "werwerew";

    (e || window.event).returnValue = confirmationMessage;
    return confirmationMessage;                          
 });
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rejoanul Alam
  • 5,435
  • 3
  • 39
  • 68

3 Answers3

0

This is actually expected. unload event in JavaScript detects any changes to the current state of the page. This implies that when you close the page or navigate away from the page, the event gets fired. You can try differentiating to some extent as to whether the user has clicked to navigate away from the page or the browser is closed, but to tell you the truth, there is no perfect way of trapping browser close. The following function does this to some extent

window.onbeforeunload = function (event) {
    var message = 'You are about to close the browser window';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a, button, input[type='submit']").click(function () {
        window.onbeforeunload = null;
    });
});

Or, if you wish to implement the browser close functionality in a better way, go for JQuery Popups

ArinCool
  • 1,720
  • 1
  • 13
  • 24
0

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;
Rupak
  • 17
  • 1
  • 1
  • 5
-1

I use this method when I need to send ajax before closing the tab (and in all the other cases: page refresh, back button or browser closed). but if you set an amount of time large enough, you are quite sure that your code is being executed before closing the tab.

 window.addEventListener('beforeunload', function (e) {
  //Your code ........ajax call 

   var start = Date.now(), now = start;
   var delay = 200; // msec
   while (now - start < delay) {
       now = Date.now();
   }
   delete e['returnValue'];
 });