Rectangle 27 0

javascript Detect browser or tab closing?


<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}
window.onbeforeunload = "alert('wait... chrome!')"
window.onunload = "alert('wait')"

//This is working in IE7, if you are closing tab or browser with only one tab

It turns out that using this code in IE9 will cause this message to pop up when the user clicks the back, forward, or refresh buttons with their mouse.

Just a heads up that we implemented a similar solution back in 2007. This solution no longer works in IE9 as of about a week ago. It stopped working (or possibly never worked) in tabbed browsers long ago.

window.onunload = "alert('wait')" and suchlike should not work really. "The function should assign a string value to the returnValue property of the Event object and return the same string". Please take a look at MDN article

ya. but for multiple tab browser like ie8, firefox. there is problem using this?

Note
Rectangle 27 0

javascript Detect browser or tab closing?


However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

Note
Rectangle 27 0

javascript Detect browser or tab closing?


window.addEventListener("beforeunload", function (e) {        
      $.ajax({
          type: "POST",
          url: startTimerUrl,
          async: false           
      });
      return;
    });

First, start a countdown timer on the server in the beforeunload event handler in JS. The ajax calls need to be synchronous for IE and Edge to work properly. You also need to use return; to prevent the confirmation dialog from showing like this:

I needed to automatically log the user out when the browser or tab closes, but not when the user navigates to other links. I also did not want a confirmation prompt shown when that happens. After struggling with this for a while, especially with IE and Edge, here's what I ended doing (checked working with IE 11, Edge, Chrome, and Firefox) after basing off the approach by this answer.

Implementation note: I'm using ASP.NET MVC 5 and I'm cancelling logout in an overridden Controller.OnActionExecuted() method.

Starting the timer sets the cancelLogout flag to false. If the user refreshes the page or navigates to another internal link, the cancelLogout flag on the server is set to true. Once the timer event elapses, it checks the cancelLogout flag to see if the logout event has been cancelled. If the timer has been cancelled, then it would stop the timer. If the browser or tab was closed, then the cancelLogout flag would remain false and the event handler would log the user out.

Note
Rectangle 27 0

javascript Detect browser or tab closing?


window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

Best Answer Works in all the browser

For some reasons, Webkit-based browsers don't follow the spec for the dialog box. An almost cross-working example would be close from the below example.

This example for handling all browsers.

This is the only solution that worked for my chrome browser. I didn't try any others.

This method is not working perfectly on tab close while using firefox (>= ver. 44) with only tab opened.

yee, i try a lot of solutions and i come with this at end, combination for best answers, and i tests it on all browsers.

Note
Rectangle 27 0

javascript Detect browser or tab closing?


Correct. You can only detect when the page is unloaded, not when the window is closed. Also, the onbeforeunload is non-standard, so it's not supported by all browsers.

I wanted to use the 'on close' feature as well, but noticed that my users will occasionally refresh the screen by pressing F5. Since my 'on close' handlers are invoked on such refresh, this means I can't use it the way I needed it (which was a true 'close tab or window')... damn it, we need a new event model for all of this!

If I get you correctly, you want to know when a tab/window is effectively closed. Well, AFAIK the only way in Javascript to detect that kind of stuffs are onunload & onbeforeunload events.

Of course this will still work, they just removed a custom String return value from onbeforeunload. So now you're no longer be able to display a custom message before unloading.

This works for me. However, my issue is a little more complicated. I'm trying to pass parameters into a method I assign to onbeforeunload from the codebehind. Could someone stop by stackoverflow.com/questions/28305430/ and weigh in?

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

Note
Rectangle 27 0

javascript Detect browser or tab closing?


window.onbeforeunload = function () {
    return "Do you really want to close?";
};

What kind of sorcery is this? (y) does it works on all browsers? works great on chrome

very simple and clean solution. (y)

Note
Rectangle 27 0

javascript Detect browser or tab closing?


$(window).on('beforeunload', function(){ alert ('Bye now')});
$(window).unload( function () { alert("Bye now!"); } );
beforeunload

as per jQuery docs "Most browsers will ignore calls to alert(), confirm() and prompt()" api.jquery.com/unload

Note
Rectangle 27 0

javascript Detect browser or tab closing?


<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}
window.onbeforeunload = "alert('wait... chrome!')"
window.onunload = "alert('wait')"

//This is working in IE7, if you are closing tab or browser with only one tab

It turns out that using this code in IE9 will cause this message to pop up when the user clicks the back, forward, or refresh buttons with their mouse.

Just a heads up that we implemented a similar solution back in 2007. This solution no longer works in IE9 as of about a week ago. It stopped working (or possibly never worked) in tabbed browsers long ago.

window.onunload = "alert('wait')" and suchlike should not work really. "The function should assign a string value to the returnValue property of the Event object and return the same string". Please take a look at MDN article

ya. but for multiple tab browser like ie8, firefox. there is problem using this?

Note
Rectangle 27 0

javascript Detect browser or tab closing?


if(myWindow.closed){do things}

Note: Polling anything is generally not the best solution. The window.onbeforeunload event should be used if possible, the only caveat being that it also fires if you navigate away.

There is no event, but there is a property window.closed which is supported in all major browsers as of the time of this writing. Thus if you really needed to know you could poll the window to check that property.

Note
Rectangle 27 0

javascript Detect browser or tab closing?


However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

Note