92

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?

Thomas
  • 6,291
  • 6
  • 40
  • 69
vjeta
  • 1,178
  • 2
  • 11
  • 18
  • 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 '13 at 06: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 '13 at 06:57
  • 1
    `$(window).unload(function(){var e=confirm("Are you sure you want to exit?");if(e){}})` – Surjith S M Dec 31 '13 at 07:01
  • You can't detect the browser's closing as such, only the closing of the current document. – Pekka Jan 01 '14 at 05:25
  • possible duplicate of [Browser window close event](http://stackoverflow.com/questions/1631959/browser-window-close-event) – Pekka Jan 01 '14 at 05:26
  • possible duplicate of [How to capture browser close event in javascript?](http://stackoverflow.com/questions/6622461/how-to-capture-browser-close-event-in-javascript) – Jewels Mar 02 '15 at 09:52
  • If you want to be extremely precise, please check this solution: https://stackoverflow.com/questions/76139970/trying-to-detect-browser-close-event-using-signalr – Behnam Faghih May 03 '23 at 07:04

11 Answers11

94

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.

Community
  • 1
  • 1
Ravimallya
  • 6,550
  • 2
  • 41
  • 75
  • @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 01 '15 at 12:40
  • I'm not sure whether it is possible or not. As of I know it is not possible. However, can you post a new question with the reference to this answer, so that what community will say. – Ravimallya Aug 03 '15 at 04:37
  • @Bit_hunter, you could execute a function where you show a custom div where the user can press Yes or No – Black Apr 12 '16 at 07:11
  • 1
    Is there a way to avoid the message when the page is refreshed? – oracleruiz Jun 20 '16 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 '16 at 05:17
  • 1
    it does not show with custom messages, only message default of browser – huykon225 Jul 05 '17 at 07: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 '20 at 15:48
54

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

Homer
  • 355
  • 1
  • 5
  • 17
shiv
  • 669
  • 6
  • 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 – Aitazaz Khan Nov 27 '15 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 04 '16 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? – Milind Thakkar Aug 01 '16 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 . :-( – Milind Thakkar Aug 02 '16 at 06:12
  • @Shiv as you aid for custmizing message, return "my custommessage" is not working may be because of this https://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx – Devjosh Sep 15 '16 at 07:10
  • This seems to work great! I'm sending a last Google Analytics event to measure more precisely time on the last page of a session. – Nico May 18 '17 at 16:51
  • @NicoDurand the [sendBeacon](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon) is more of use there – Poul Kruijt Sep 05 '17 at 09:46
  • This was exactly what I was looking for!! – Sukanya Pai Sep 06 '19 at 05:56
  • Very nice code. I have only one issue that CTRL+F4 and Ctrl+w. ConfirmLeave() is not call. browser close before function call. function ConfirmLeave() { debugger; var endchat = confirm( "Do u want to end chat now?" ); if ( endchat == true ) { var email = confirm( "Do u want to email chat ?" ); if ( email ) { $( "#btnEndChat" ).click(); } else { return false; } } else { return false; } } – Purvi Pandya Sep 17 '19 at 10:18
  • 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 '20 at 19:24
  • In my Firefox 95 this only works when I actually did something on the page, so in the usual testing practice (open the page, try to close it) it will fail. Open the page, click once (as you would do if you actually were using the page) and then try to close it. – Iziminza Dec 28 '21 at 11:16
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

Khamidulla
  • 2,927
  • 6
  • 35
  • 59
  • Sorry, In ubuntu I do not have Mozilla 33. So you can look up jsfiddle's implementation – Khamidulla Oct 28 '14 at 10:10
  • Fiddle url is not working anymore.please check and update – Shashank Vivek Jan 22 '17 at 08: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 '17 at 08:54
  • Blocked confirm('Do you really want to close?') during beforeunload. – Amin Rahimi Jul 09 '18 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 '21 at 00: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

wutzebaer
  • 14,365
  • 19
  • 99
  • 170
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.

Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265
  • I would like detect only when the user closes tab or navigator and Alt+F4. – Kiquenet Jul 08 '15 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) – Matas Vaitkevicius Jul 08 '15 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 – Aitazaz Khan Nov 27 '15 at 14:20
  • 1
    Is there a way to avoid the message when the page is refreshed? – oracleruiz Jun 20 '16 at 16:31
  • I was looking to detect the close event for an HTA app, this solution worked perfectly. – freginold Nov 17 '16 at 15:08
  • I know this is an old answer and currently this is the only thing that is triggering when I close, refresh, etc. But can I run a function first after clicking leave/ok and before the actual page closes? – rod james Jun 30 '21 at 00:21
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

Macondo
  • 166
  • 6
1

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

$(window).on("beforeunload", function() {
    runBeforeClose();
});
ow3n
  • 5,974
  • 4
  • 53
  • 51
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...

manufosela
  • 469
  • 6
  • 8
  • 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 '16 at 07: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 '16 at 09:42
  • But this won't work on mobile browsers anyway, so the solution is not the yellow from the egg. – Black Apr 14 '16 at 06:27
  • Of course, this approach it isn't a solution to mobile browsers – manufosela Apr 15 '16 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.

user2753425
  • 301
  • 2
  • 9
-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

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.

Salvador P.
  • 1,469
  • 19
  • 16