[javascript] Trying to detect browser close event

I have tried many methods to detect browser close event through jQuery or JavaScript. But, unfortunately, I have not been able to detect the close. The onbeforeunload and onunload methods are also not working.

How do I detect the window close, unload, or beforeunload events?

This question is related to javascript jquery browser

The answer is


Referring to various articles and doing some trial and error testing, finally I developed this idea which works perfectly for me.

The idea was to detect the unload event that is triggered by closing the browser. In that case, the mouse will be out of the window, pointing out at the close button ('X').

$(window).on('mouseover', (function () {
    window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
    window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
    return "";
}
var prevKey="";
$(document).keydown(function (e) {            
    if (e.key=="F5") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
        window.onbeforeunload = ConfirmLeave;   
    }
    else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
        window.onbeforeunload = ConfirmLeave;
    }
    else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
        window.onbeforeunload = ConfirmLeave;
    }
    prevKey = e.key.toUpperCase();
});

The ConfirmLeave function will give the pop up default message, in case there is any need to customize the message, then return the text to be displayed instead of an empty string in function ConfirmLeave().


Following script will give message on Chrome and IE:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome
enter image description here

IE
enter image description here

on Firefox you will get generic message

enter image description here

Mechanism is synchronous so no server calls to delay will work, you still can prepare a mechanism like modal window that is shown if user decides to stay on page, but no way to prevent him from leaving.

Response to question in comment

F5 will fire event again, so will Atl+F4.


You can try something like this.

<html>
<head>
    <title>test</title>
    <script>
        function openChecking(){
            // alert("open");
            var width = Number(screen.width-(screen.width*0.25));  
            var height = Number(screen.height-(screen.height*0.25));
            var leftscr = Number((screen.width/2)-(width/2)); // center the window
            var topscr = Number((screen.height/2)-(height/2));
            var url = "";
            var title = 'popup';
            var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
            var popup = window.open(url, title, properties);
            var crono = window.setInterval(function() {
                if (popup.closed !== false) { // !== opera compatibility reasons
                    window.clearInterval(crono);
                    checkClosed();
                }
            }, 250); //we check if the window is closed every 1/4 second
        }   
        function checkClosed(){
            alert("closed!!");
            // do something
        }
    </script>    
</head>
<body>
    <button onclick="openChecking()">Click Me</button>
</body>
</html>

When the user closes the window, the callback will be fired.


jQuery .bind() has been deprecated. Use .on() instead

$(window).on("beforeunload", function() {
    runBeforeClose();
});

As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,

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

more details can be found at : developer.mozilla.org


Hi i got a tricky solution, which works only on new browsers:

just open a websocket to your server, when the user closes the window, the onclose event will be fired


Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return confirm("Do you really want to close?"); 
    });
});

For simple follow following steps:

  1. open http://jsfiddle.net/
  2. enter something into html, css or javascript box
  3. try to close tab in chrome

It should show following picture:

enter image description here


<script type="text/javascript">
window.addEventListener("beforeunload", function (e) {

  var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
  (e || window.event).returnValue = confirmationMessage;
  return confirmationMessage;

});
</script>

Please try this code, this is working fine for me. This custom message is coming into Chrome browser but in Mozilla this message is not showing.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

<script type="text/javascript" language="javascript">

var validNavigation = false;

function endSession() {
// Browser or broswer tab is closed
// Do sth here ...
alert("bye");
}

function wireUpEvents() {
/*
* For a list of events that triggers onbeforeunload on IE
* check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
*/
window.onbeforeunload = function() {
  if (!validNavigation) {

            var ref="load";
      $.ajax({
            type: 'get',
            async: false,
            url: 'logout.php',
 data:
            {
                ref:ref               
            },
             success:function(data)
            {
                console.log(data);
            }
            });
     endSession();
  }
 }

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

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();  
}); 
</script> 

This is used for when logged in user close the browser or browser tab it will automatically logout the user account...


Maybe it's better to use the path detecting mouse.

In BrowserClosureNotice you have a demo example and pure javascript library to do it.

It isn't perfect, but avoid problems of document or mouse events...


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)