356
votes

Is there any cross-browser JavaScript/jQuery code to detect if the browser or a browser tab is being closed, but not due to a link being clicked?

21
See my answer to this question: stackoverflow.com/questions/3735198/…Nivas
Use sessionStorage Property, it will expire once the browser closes. w3schools.com/jsref/prop_win_sessionstorage.aspcsandreas1
Check this answer! I found it extremely useful and covers majority of the cases. stackoverflow.com/a/26275621/7192927Sukanya Pai

21 Answers

309
votes

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.

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.

146
votes

From MDN Documentation

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.

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

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

This example for handling all browsers.

58
votes

Simple Solution

window.onbeforeunload = function () {
    return "Do you really want to close?";
};
23
votes
<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') ;
    }   
}

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

15
votes

For similar tasks, you can use sessionStorage to store data locally until the browser tab is closed.

The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).(W3Schools)

This is my pen.

<div id="Notice">
    <span title="remove this until browser tab is closed"><u>dismiss</u>.</span>
</div>
<script>
    $("#Notice").click(function() {
     //set sessionStorage on click
        sessionStorage.setItem("dismissNotice", "Hello");
        $("#Notice").remove();
    });
    if (sessionStorage.getItem("dismissNotice"))
    //When sessionStorage is set Do stuff...
        $("#Notice").remove();
</script>
13
votes

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.

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:

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

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.

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

9
votes

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.

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.

9
votes

I found a way, that works on all of my browsers.

Tested on following versions: Firefox 57, Internet Explorer 11, Edge 41, one of the latested Chrome (it won't show my version)

Note: onbeforeunload fires if you leave the page in any way possible (refresh, close browser, redirect, link, submit..). If you only want it to happen on browser close, simply bind the event handlers.

  $(document).ready(function(){         

        var validNavigation = false;

        // Attach the event keypress to exclude the F5 refresh (includes normal 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;
        }); 

        window.onbeforeunload = function() {                
            if (!validNavigation) {     
                // ------->  code comes here
            }
        };

  });
8
votes

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.

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.

6
votes
$(window).unload( function () { alert("Bye now!"); } );
4
votes

Since no one has mentioned it yet (8+ years later): A WebSocket can be another effective way to detect a closed tab. As long as the tab is open and pointed at the host, the client is able to maintain an active WebSocket connection to the host.

Caveat: Please note that this solution is really only viable for a project if a WebSocket doesn't require any additional significant overhead from what you are already doing.

Within a sensible timeout period (e.g. 2 minutes), the server side can determine that the client has gone away after the WebSocket has disconnected and perform whatever action is desired such as removing uploaded temp files. (In my extremely specialized use-case, my goal was to terminate a localhost app server three seconds after the WebSocket connection drops and all CGI/FastCGI activity terminates - any other keep-alive connections don't affect me.)

I had problems getting the onunload event handler to work properly with beacons (as recommended by this answer). Closing the tab did not appear to trigger the beacon and open tabs triggered it in ways that could potentially cause problems. A WebSocket solved the problem I was running into more cleanly because the connection closes roughly around the same time that the tab closes and switching pages within the application simply opens a new WebSocket connection well within the delay window.

4
votes

onunload is the answer for Chrome. According to caniuse its crossbrowser. But not all browsers react the same.

window.onunload = function(){
    alert("The window is closing now!");
}

developer.mozilla.org

These events fire when the window is unloading its content and resources.

For Chrome:

onunload executes only on page close. It doesn't execute even on page refresh and on navigating to a different page.

For Firefox v86.0:

It wouldn't execute at all. Page refresh, navigating away, closing browser tab, closing browser, nothing.

2
votes
window.onbeforeunload = function() {
  console.log('event');
  return false; //here also can be string, that will be shown to the user
}
2
votes
window.addEventListener("beforeunload", function (e) {
 var confirmationMessage = "tab close";

 (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
 sendkeylog(confirmationMessage);
 return confirmationMessage;                                //Webkit, Safari, Chrome etc.
}); 
2
votes
//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});

JSFiddle Link

Hi all, I was able to achieve 'Detect Browser and Tab Close Event' clicks by using browser local storage and timestamp. Hope all of you will get solved your problems by using this solution.

After my initial research i found that when we close a browser, the browser will close all the tabs one by one to completely close the browser. Hence, i observed that there will be very little time delay between closing the tabs. So I taken this time delay as my main validation point and able to achieve the browser and tab close event detection.

I tested it on Chrome Browser Version 76.0.3809.132 and found working

:) Vote Up if you found my answer helpful....

2
votes

I have tried all above solutions, none of them really worked for me, specially because there are some Telerik components in my project which have 'Close' button for popup windows, and it calls 'beforeunload' event. Also, button selector does not work properly when you have Telerik grid in your page (I mean buttons inside the grid) So, I couldn't use any of above suggestions. Finally this is the solution worked for me. I have added an onUnload event on the body tag of _Layout.cshtml. Something like this:

<body onUnload="LogOff()">

and then add the LogOff function to redirect to Account/LogOff which is a built-in method in Asp.Net MVC. Now, when I close the browser or tab, it redirect to LogOff method and user have to login when returns. I have tested it in both Chrome & Firefox. And it works!

  function LogOff() {
        $.ajax({
            url: "/Account/LogOff",
            success: function (result) {

                                        }
               });
       }
1
votes
window.onbeforeunload = function ()
{       

    if (isProcess > 0) 
    {
        return true;       
    }   

    else
    { 
        //do something      
    }
}; 

This function show a confirmation dialog box if you close window or refresh page during any process in browser.This function work in all browsers.You have to set isProcess var in your ajax process.

1
votes

It is possible to check it with the help of window.closed in an event handler on 'unload' event like this, but timeout usage is required (so result cannot be guaranteed if smth delay or prevent window from closure):

Example of JSFiddle (Tested on lates Safari, FF, Chrome, Edge and IE11 )

var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
   <head><title>CHILD WINDOW/TAB</title></head>
   <body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
    document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
    document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
    setTimeout(()=>{
        document.querySelector('.status').innerHTML +=  getChildWindowStatus();
    },1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
    alert(getChildWindowStatus());
}
function getChildWindowStatus() {
  if (win.closed) { 
      return 'Child window has been closed!';
  } else {
      return 'Child window has not been closed!';
  }
}
-1
votes

As @jAndy mentioned, there is no properly javascript code to detect a window being closed. I started from what @Syno had proposed.

I had pass though a situation like that and provided you follow these steps, you'll be able to detect it.
I tested it on Chrome 67+ and Firefox 61+.

var wrapper = function () { //ignore this

var closing_window = false;
$(window).on('focus', function () {
    closing_window = false; 
   //if the user interacts with the window, then the window is not being 
   //closed
});

$(window).on('blur', function () {

    closing_window = true;
    if (!document.hidden) { //when the window is being minimized
        closing_window = false;
    }
    $(window).on('resize', function (e) { //when the window is being maximized
        closing_window = false;
    });
    $(window).off('resize'); //avoid multiple listening
});

$('html').on('mouseleave', function () {
    closing_window = true; 
    //if the user is leaving html, we have more reasons to believe that he's 
    //leaving or thinking about closing the window
});

$('html').on('mouseenter', function () {
    closing_window = false; 
    //if the user's mouse its on the page, it means you don't need to logout 
    //them, didn't it?
});

$(document).on('keydown', function (e) {

    if (e.keyCode == 91 || e.keyCode == 18) {
        closing_window = false; //shortcuts for ALT+TAB and Window key
    }

    if (e.keyCode == 116 || (e.ctrlKey && e.keyCode == 82)) {
        closing_window = false; //shortcuts for F5 and CTRL+F5 and CTRL+R
    }
});

// Prevent logout when clicking in a hiperlink
$(document).on("click", "a", function () {
    closing_window = false;
});

// Prevent logout when clicking in a button (if these buttons rediret to some page)
$(document).on("click", "button", function () {
    closing_window = false;

});
// Prevent logout when submiting
$(document).on("submit", "form", function () {
    closing_window = false;
});
// Prevent logout when submiting
$(document).on("click", "input[type=submit]", function () {
    closing_window = false;
});

var toDoWhenClosing = function() {

    //write a code here likes a user logout, example: 
    //$.ajax({
    //    url: '/MyController/MyLogOutAction',
    //    async: false,
    //    data: {

    //    },
    //    error: function () {
    //    },
    //    success: function (data) {
    //    },
    //});
};


window.onbeforeunload = function () {
    if (closing_window) {
        toDoWhenClosing();
    }
};

};

-2
votes

try this, I am sure this will work for you.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type='text/javascript'>
    $(function() {

        try{
            opera.setOverrideHistoryNavigationMode('compatible');
            history.navigationMode = 'compatible';
        }catch(e){}

        function ReturnMessage()
        {
            return "wait";
        }

        function UnBindWindow()
        {
            $(window).unbind('beforeunload', ReturnMessage);
        }

        $(window).bind('beforeunload',ReturnMessage );
    });
</script>
-3
votes

Try this. It will work. jquery unload method is depreceted.

window.onbeforeunload = function(event) {
    event.returnValue = "Write something clever here..";
};