Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the browser window close event?

People also ask

How do I find close browser events?

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.

How do I stop a browser window from closing?

Use the Pin tab option to keep Prevent Close available in Chrome. To make this as painless as possible, I recommend pinning this website to your browser then moving the tab out of the way. To do that open Prevent Close, and then right-click the tab with your mouse. From the context menu select Pin tab.

How do you handle browser tab close angular not close refresh?

The best way I found to reload the page without losing cookies, and remove cookies on window or tab close was to use ng-keydown to watch the F5 Keypress (KeyCode 116).

How do I close the HTML window automatically?

open("URL_HERE", "my_window", "height=100,width=100"); and we need to close the second page automatically after login success. Okay so in the popup use window. close() to close the window like I mentoined in my example.


The beforeunload event fires whenever the user leaves your page for any reason.

For example, it will be fired if the user submits a form, clicks a link, closes the window (or tab), or goes to a new page using the address bar, search box, or a bookmark.

You could exclude form submissions and hyperlinks (except from other frames) with the following code:

var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });

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

For jQuery versions older than 1.7, try this:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

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

The live method doesn't work with the submit event, so if you add a new form, you'll need to bind the handler to it as well.

Note that if a different event handler cancels the submit or navigation, you will lose the confirmation prompt if the window is actually closed later. You could fix that by recording the time in the submit and click events, and checking if the beforeunload happens more than a couple of seconds later.


Maybe just unbind the beforeunload event handler within the form's submit event handler:

jQuery('form').submit(function() {
    jQuery(window).unbind("beforeunload");
    ...
});

For a cross-browser solution (tested in Chrome 21, IE9, FF15), consider using the following code, which is a slightly tweaked version of Slaks' code:

var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });

$(window).bind('beforeunload', function(eventObject) {
    var returnValue = undefined;
    if (! inFormOrLink) {
        returnValue = "Do you really want to close?";
    }
    eventObject.returnValue = returnValue;
    return returnValue;
}); 

Note that since Firefox 4, the message "Do you really want to close?" is not displayed. FF just displays a generic message. See note in https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload


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

My answer is aimed at providing simple benchmarks.

HOW TO

See @SLaks answer.

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

How long does the browser take to finally shut your page down?

Whenever an user closes the page (x button or CTRL + W), the browser executes the given beforeunload code, but not indefinitely. The only exception is the confirmation box (return 'Do you really want to close?) which will wait until for the user's response.

Chrome: 2 seconds.
Firefox: ∞ (or double click, or force on close)
Edge: ∞ (or double click)
Explorer 11: 0 seconds.
Safari: TODO

What we used to test this out:

  • A Node.js Express server with requests log
  • The following short HTML file

What it does is to send as many requests as it can before the browser shut downs its page (synchronously).

<html>
<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
    function request() {
        return $.ajax({
            type: "GET",
            url: "http://localhost:3030/" + Date.now(),
            async: true
        }).responseText;
    }
    window.onbeforeunload = () => {
        while (true) {
            request();
        }
        return null;
    }
    </script>
</body>
</html>

Chrome output:

GET /1480451321041 404 0.389 ms - 32  
GET /1480451321052 404 0.219 ms - 32  
...  
GET /hello/1480451322998 404 0.328 ms - 32

1957ms ≈ 2 seconds // we assume it's 2 seconds since requests can take few milliseconds to be sent.