Detect browser/tab closing

I know how to display an alert to the user if they attempt to navigate away from the current page asking them if they are sure they wish to do so but I was wondering if there is a way to display this alert ONLY when the window / tab is being closed? I'd like to only have the confirmation display when the window or tab is being closed, not when the user clicks a link.

Not possible.

the only thing close is the onbeforeunload event, but there isn't a difference (to javascript) between a closed window/tab or a navigation to another page.

Follow-up:

I suppose you could attach a click handler to every anchor on the page and use a "dirty" flag, but that's really hack-ish. something like (forgive me, but using jquery for simplicity):

(function(){
  var closingWindow = true;
  $('a').on('click', function(){
    if (this.href == /* on-domain link */){
      closingWindow = false;
    }
  });
  $(window).on('beforeunload',function(){
    if (closingWindow){
      // your alert
    }
  });
})();

but that's about as close as you're going to get. note: this isn't going to help if another javascript function uses window.location, etc.

Detect browser or tab closing, 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� A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser. The addEventListener () method is used to set up a function whenever a certain event occurs.

You cannot differentiate between the two.

window.onbeforeunload is triggered immediately before the browser unloads its resources. You do not know the reason for the unload, only that it's about to occur:

From the MDN:

An event that fires when a window is about to unload its resources. The document is still visible and the event is still cancelable.

Trying to detect browser close event, enter something into html, css or javascript box; try to close tab in chrome. It should show following picture: enter image description here. Way to detect browser or tab close event 1. Perform database operation before close the browser (without alert) Here, we will use the addEventListener () method 2. Show alert before close/reload the tab or browser

How about doing something like this?

  1. Have a global variable set to false (i.e. var hasCLickedLink = false;)

  2. On all your links (<a>), attach an event handler that sets the variable to true

  3. On onbeforeunload, check the value of the variable to see if a link has been clicked or not. If it is still false, then they haven't clicked a link so give them the alert.

How to know a browser tab close or refresh with JavaScript, There are many other situations where you can use it. In this post, I discuss How you can detect Browser Tab close and refresh using JavaScript. Questions: 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? Answers: 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

You need to explicitly specify events for which you don't want to show confirmation dialogue box.

var validNavigation = 0;

function bindDOMEvents() {
    // Attach the event keypress to exclude the F5 refresh
    $(document).keydown(function(e)
    {
        var key = e.which || e.keyCode;
        if (key == 116)
        {
            validNavigation = 1;
        };
    });
    // Attach the event click for all links in the page
    $("a").bind("click", function()
    {
        validNavigation = 1;
    });
    // Attach the event submit for all forms in the page
    $("form").bind("submit", function()
    {
        validNavigation = 1;
    });
    // Attach the event click for all inputs in the page
    $("input[type=submit]").bind("click", function()
    {
        validNavigation = 1;
    });
};
$(document).ready(function()
{
    bindDOMEvents();
    window.onbeforeunload = function () {
        console.log(validNavigation);
        if (validNavigation == '1')
        {
            console.log("No Alert.. Continue");
        }
        else
        {
            return false;
        }
    };
});

I need to detect tab close and browser close event - Get Help, Hi everyone When the user close tab or browser, I need to remove token from localStoroge but beforeunload and unbeforeunload fired also in� onunload will tell you that either a close-tab / close-window / refresh / reload has occurred. The second solution I posted above shows how to detect it’s a refresh / reload. Exclude the 2nd from the 1st and you have what you want -> do something only if it’s a close-tab / close-window

This solution worked for me in Firefox with Violentmonkey. It is used like most of all window.onbeforeunload and check if left mouse button was pressed. So if pressed, this mean, click at free space or link opens - not closing tab.

    function DetectBrowserExit()
{
  if (butpres == 0)  {
   //your action before closing tab, alert not showing
  }
}

window.onbeforeunload = function(){ DetectBrowserExit(); }

// the key is pressed, then when window.onbeforeunload - link is opening, so, tab not closing 

        document.addEventListener('mousedown',function(e){
            if (e.which == 1) { //1-lbutton 2-mb 3-rb
                //e.preventDefault();
        butpres = 1
        setTimeout(function() {
          butpres = 0 //if after 3 seconds the script still works then the link has not been clicked, clear the click and continue to catch new clicks 

          //alert(butpres);
          }, 3000); //Two seconds will elapse and Code will execute.
         //alert(butpres);
                //command_lock();
            }
        },false);

Detect browser or tab close event using javascript and perform , Hi, I want to update flag in database when user logout. I am doing it when user logout using logout button. I want to same when user close browser or tab. How to� For now i able to detect the browser close and redirect the user to other pages. I am using ASP.NET to build my website, and i have multiple child pages under the same master page. The problem i faced is whenever i swift to another child page (under the same master page) will redirect me to go Thanks.aspx page.

How to detect browser or tab closing ?, Is there any JavaScript code to detect if the browser or a browser tab is being closed? Hello Kabir, if you want to close only active tab and need to keep the browser window open, you can make use of switch_to.window method which has the input parameter as window handle-id.

[CLOSED] Solution How to detect browser/tab close – Wisej, here my working solution for detect when user close browser or a broser tab. The real trick is to add jquery before load wisej in default.html. Using JavaScript onbeforeunload event, you can detect browser or tab close event and update the user online status in the database. The following JavaScript code could detect the browser close event as well as tab close event. < script > window. onbeforeunload = function () { //Ajax request to update the database $.ajax ( { type: "POST" , url: "updateUserStatus.php" }); } < /script >.

javascript detect browser close tab browser, Please try is as below. Note: This is just a sample.Adjust it according to your app. Hide Copy Code. window.addEventListener("beforeunload"� How to detect browser or tab closing ? Ask a question+. 4. Is there any JavaScript code to detect if the browser or a browser tab is being closed?

Comments
  • I was afraid of that... thank you for the help anyways!
  • Nice solution, but it won't catch back and forwards button clicks.