94

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?

7
  • I don't want to close the browser, I want to detect the close event. What I tried is window.onbeforeunload = function (e) { var message = "Your confirmation message goes here.", e = e || window.event; // For IE and Firefox if (e) { e.returnValue = message; } // For Safari return message; };
    – vjeta
    Dec 31, 2013 at 6:54
  • By "close," do you mean exiting the browser application completely or simply closing a tab or window? Of course, closing the last open tab or window is probably the same depending on the browser. However, it would still help to be clear on your meaning.
    – Ned
    Dec 31, 2013 at 6:57
  • 1
    $(window).unload(function(){var e=confirm("Are you sure you want to exit?");if(e){}}) Dec 31, 2013 at 7:01
  • You can't detect the browser's closing as such, only the closing of the current document.
    – Pekka
    Jan 1, 2014 at 5:25
  • possible duplicate of Browser window close event
    – Pekka
    Jan 1, 2014 at 5:26

11 Answers 11

95

Have you tried this code?

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#lnkLogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});

The second function is optional to avoid prompting while clicking on #lnkLogOut and .btn elements.

One more thing, The custom Prompt will not work in Firefox (even in latest version also). For more details about it, please go to this thread.

7
  • @Ravi Code is fine. But I want to fire logout function if user click on "Leave this page". But how can I detect whether user has clicked "Leave this page" or not?
    – Bit_hunter
    Aug 1, 2015 at 12:40
  • 1
    Is there a way to avoid the message when the page is refreshed?
    – oracleruiz
    Jun 20, 2016 at 16:31
  • 1
    @oracleruiz as far as I know, the answer would be NO unless you make window.onbeforeunload to null when you refresh the browser through an event suck as button click. The reason is window.onbeforeunload will trigger each time when the dom is being unloaded.
    – Ravimallya
    Jun 21, 2016 at 5:17
  • 1
    it does not show with custom messages, only message default of browser
    – huykon225
    Jul 5, 2017 at 7:42
  • 1
    When I close the tab the first time, it doesn't work. But when I close the tab while the developer's console is open, it works surprisingly. I believe in my case it doesn't work when the focus is on the page. Any ideas?
    – Rahul Vala
    Feb 21, 2020 at 15:48
55

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().

11
  • 1
    what about firing up ajax when user press leave page button is it possible ?? if not than what can be the alternative of it Nov 27, 2015 at 14:49
  • My favorite answer. This avoids listing all possible DOM elements that could lead you out of the page. And besides that the code also detects tab\window closing keyoard shortcuts.
    – GigiSan
    Feb 4, 2016 at 15:10
  • 1
    Hi Shiv. This seems to be working fine for most cases except for ALT+F4 when there is no other tab i.e. open the page in browser and press Alt + F4. This closes browser without message. Ctrl + F4 works in the same situation.. Any Idea? Aug 1, 2016 at 18:21
  • 1
    Also, it is firing in case you click browser back or forward as mouse is out of window for that buttons . :-( Aug 2, 2016 at 6:12
  • 2
    The solution is good, however, in my case, it seems to work only when the developer's console is open in the browser. If I click on the page (the focus is on the page), then it doesn't work. Any idea, why this is happening?
    – Rahul Vala
    Feb 20, 2020 at 19:24
13

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

5
  • Sorry, In ubuntu I do not have Mozilla 33. So you can look up jsfiddle's implementation
    – Khamidulla
    Oct 28, 2014 at 10:10
  • Fiddle url is not working anymore.please check and update Jan 22, 2017 at 8:51
  • 2
    @ShashankVivek fiddle link does working. Read answer once more. They removed "beforeunload" event handling from current version of web ui. So you will not see notification window anymore in jsfiddle. However using script upper you can still handle event by yourself. Nothing i can do.
    – Khamidulla
    Jan 23, 2017 at 8:54
  • Blocked confirm('Do you really want to close?') during beforeunload. Jul 9, 2018 at 12:41
  • Currently working in 2021, changed to on instead of bind. But I do have a question. Can we run a function when user clicks on leave??
    – rod james
    Jun 30, 2021 at 0:25
11

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

3
  • Hi, Can we show a modal window/customized pop-up on this onclose event? Aug 31, 2020 at 17:30
  • @JyotiDuhan no you can just detect it serverside
    – wutzebaer
    Sep 4, 2020 at 19:58
  • for page refresh too onclose will be called Dec 27, 2021 at 12:05
6

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.

6
  • I would like detect only when the user closes tab or navigator and Alt+F4.
    – Kiquenet
    Jul 8, 2015 at 10:31
  • @Kiquenet I just tested Alt + f4 on IE8 and it did trigger mechanism, I must have done something wrong when testing Crome it triggers on all browsers (IE, Chrome, Firefox) Jul 8, 2015 at 10:33
  • 1
    what about firing up ajax when user press leave page button is it possible ?? if not than what can be the alternative of it Nov 27, 2015 at 14:20
  • 1
    Is there a way to avoid the message when the page is refreshed?
    – oracleruiz
    Jun 20, 2016 at 16:31
  • I was looking to detect the close event for an HTA app, this solution worked perfectly.
    – freginold
    Nov 17, 2016 at 15:08
2

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

1

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

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

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...

4
  • What if the user just hovers his mouse over the close button, but never presses? And how to deal with the situation on mobile browsers?
    – Black
    Apr 12, 2016 at 7:18
  • This code detects when the mouse is going to the close button, but not detect when the close button is pressed. If you want you can add this event too. In my case I don't want to avoid the close, I want to show information if I think that you are thinking to close the page.
    – manufosela
    Apr 13, 2016 at 9:42
  • But this won't work on mobile browsers anyway, so the solution is not the yellow from the egg.
    – Black
    Apr 14, 2016 at 6:27
  • Of course, this approach it isn't a solution to mobile browsers
    – manufosela
    Apr 15, 2016 at 11:42
0
<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.

-1
<!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...

2
  • please share some explanation why this works and how it works Mar 31, 2017 at 9:20
  • This is used for when logged in user close the browser or browser tab it will automatically logout the user account.. And make changes in the data base also..... Mar 31, 2017 at 9:32
-2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.