Rectangle 27 30

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

what about firing up ajax when user press leave page button is it possible ?? if not than what can be the alternative of it

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.

Cannot read property 'toUpperCase' of undefined

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?

Also, it is firing in case you click browser back or forward as mouse is out of window for that buttons . :-(

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 51

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.

did you see any errors in console?

@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?

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.

@Bit_hunter, you could execute a function where you show a custom div where the user can press Yes or No

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 10

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?"); 
    });
});
  • enter something into html, css or javascript box
  • try to close tab in chrome

Doesnt work in Firefox v33

Sorry, In ubuntu I do not have Mozilla 33. So you can look up jsfiddle's implementation

Fiddle url is not working anymore.please check and update

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

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 168

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 & onbeforeunload events.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

Correct. You can only detect when the page is unloaded, not when the window is closed. Also, the onbeforeunload is non-standard, so it's not supported by all browsers.

I wanted to use the 'on close' feature as well, but noticed that my users will occasionally refresh the screen by pressing F5. Since my 'on close' handlers are invoked on such refresh, this means I can't use it the way I needed it (which was a true 'close tab or window')... damn it, we need a new event model for all of this!

This works for me. However, my issue is a little more complicated. I'm trying to pass parameters into a method I assign to onbeforeunload from the codebehind. Could someone stop by stackoverflow.com/questions/28305430/ and weigh in?

Of course this will still work, they just removed a custom String return value from onbeforeunload. So now you're no longer be able to display a custom message before unloading.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 164

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 & onbeforeunload events.

Unfortunately (or fortunately?), those events are also fired when you leave a site over a link or your browsers back button. So this is the best answer I can give, I don't think you can natively detect a pure close in Javascript. Correct me if I'm wrong here.

Correct. You can only detect when the page is unloaded, not when the window is closed. Also, the onbeforeunload is non-standard, so it's not supported by all browsers.

I wanted to use the 'on close' feature as well, but noticed that my users will occasionally refresh the screen by pressing F5. Since my 'on close' handlers are invoked on such refresh, this means I can't use it the way I needed it (which was a true 'close tab or window')... damn it, we need a new event model for all of this!

This works for me. However, my issue is a little more complicated. I'm trying to pass parameters into a method I assign to onbeforeunload from the codebehind. Could someone stop by stackoverflow.com/questions/28305430/ and weigh in?

Of course this will still work, they just removed a custom String return value from onbeforeunload. So now you're no longer be able to display a custom message before unloading.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 3

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?"; 
    });
});

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 3

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

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

I would like detect only when the user closes tab or navigator and Alt+F4.

@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)

what about firing up ajax when user press leave page button is it possible ?? if not than what can be the alternative of it

Is there a way to avoid the message when the page is refreshed?

I was looking to detect the close event for an HTA app, this solution worked perfectly.

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 2

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

javascript - Trying to detect browser close event - Stack Overflow

javascript jquery browser
Rectangle 27 82

For some reasons, Webkit-based browsers don't follow the spec for the dialog box. An almost cross-working example would be close from the below example.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

This example for handling all browsers.

This is the only solution that worked for my chrome browser. I didn't try any others.

yee, i try a lot of solutions and i come with this at end, combination for best answers, and i tests it on all browsers.

This method is not working perfectly on tab close while using firefox (>= ver. 44) with only tab opened.

Best Answer Works in all the browser

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 82

For some reasons, Webkit-based browsers don't follow the spec for the dialog box. An almost cross-working example would be close from the below example.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

This example for handling all browsers.

This is the only solution that worked for my chrome browser. I didn't try any others.

yee, i try a lot of solutions and i come with this at end, combination for best answers, and i tests it on all browsers.

This method is not working perfectly on tab close while using firefox (>= ver. 44) with only tab opened.

Best Answer Works in all the browser

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 33

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

very simple and clean solution. (y)

What kind of sorcery is this? (y) does it works on all browsers? works great on chrome

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 33

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

very simple and clean solution. (y)

What kind of sorcery is this? (y) does it works on all browsers? works great on chrome

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 13

<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}

//This is working in IE7, if you are closing tab or browser with only one tab

ya. but for multiple tab browser like ie8, firefox. there is problem using this?

It turns out that using this code in IE9 will cause this message to pop up when the user clicks the back, forward, or refresh buttons with their mouse.

Just a heads up that we implemented a similar solution back in 2007. This solution no longer works in IE9 as of about a week ago. It stopped working (or possibly never worked) in tabbed browsers long ago.

window.onunload = "alert('wait')"
window.onbeforeunload = "alert('wait... chrome!')"

window.onunload = "alert('wait')" and suchlike should not work really. "The function should assign a string value to the returnValue property of the Event object and return the same string". Please take a look at MDN article

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 13

<body onbeforeunload="ConfirmClose()" onunload="HandleOnClose()">

var myclose = false;

function ConfirmClose()
{
    if (event.clientY < 0)
    {
        event.returnValue = 'You have closed the browser. Do you want to logout from your application?';
        setTimeout('myclose=false',10);
        myclose=true;
    }
}

function HandleOnClose()
{
    if (myclose==true) 
    {
        //the url of your logout page which invalidate session on logout 
        location.replace('/contextpath/j_spring_security_logout') ;
    }   
}

//This is working in IE7, if you are closing tab or browser with only one tab

ya. but for multiple tab browser like ie8, firefox. there is problem using this?

It turns out that using this code in IE9 will cause this message to pop up when the user clicks the back, forward, or refresh buttons with their mouse.

Just a heads up that we implemented a similar solution back in 2007. This solution no longer works in IE9 as of about a week ago. It stopped working (or possibly never worked) in tabbed browsers long ago.

window.onunload = "alert('wait')"
window.onbeforeunload = "alert('wait... chrome!')"

window.onunload = "alert('wait')" and suchlike should not work really. "The function should assign a string value to the returnValue property of the Event object and return the same string". Please take a look at MDN article

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 5

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 5

Sorry, I was not able to add a comment to one of existing answers, but in case you wanted to implement a kind of warning dialog, I just wanted to mention that any event handler function has an argument - event. In your case you can call event.preventDefault() to disallow leaving the page automatically, then issue your own dialog. I consider this a way better option than using standard ugly and insecure alert(). I personally implemented my own set of dialog boxes based on kendoWindow object (Telerik's Kendo UI, which is almost fully open-sourced, except of kendoGrid and kendoEditor). You can also use dialog boxes from jQuery UI. Please note though, that such things are asynchronous, and you will need to bind a handler to onclick event of every button, but this is all quite easy to implement.

However, I do agree that the lack of the real close event is terrible: if you, for instance, want to reset your session state at the back-end only on case of the real close, it's a problem.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 2

$(window).unload( function () { alert("Bye now!"); } );
beforeunload
$(window).on('beforeunload', function(){ alert ('Bye now')});

as per jQuery docs "Most browsers will ignore calls to alert(), confirm() and prompt()" api.jquery.com/unload

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 2

$(window).unload( function () { alert("Bye now!"); } );
beforeunload
$(window).on('beforeunload', function(){ alert ('Bye now')});

as per jQuery docs "Most browsers will ignore calls to alert(), confirm() and prompt()" api.jquery.com/unload

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 3

I needed to automatically log the user out when the browser or tab closes, but not when the user navigates to other links. I also did not want a confirmation prompt shown when that happens. After struggling with this for a while, especially with IE and Edge, here's what I ended doing (checked working with IE 11, Edge, Chrome, and Firefox) after basing off the approach by this answer.

First, start a countdown timer on the server in the beforeunload event handler in JS. The ajax calls need to be synchronous for IE and Edge to work properly. You also need to use return; to prevent the confirmation dialog from showing like this:

window.addEventListener("beforeunload", function (e) {        
      $.ajax({
          type: "POST",
          url: startTimerUrl,
          async: false           
      });
      return;
    });

Starting the timer sets the cancelLogout flag to false. If the user refreshes the page or navigates to another internal link, the cancelLogout flag on the server is set to true. Once the timer event elapses, it checks the cancelLogout flag to see if the logout event has been cancelled. If the timer has been cancelled, then it would stop the timer. If the browser or tab was closed, then the cancelLogout flag would remain false and the event handler would log the user out.

Implementation note: I'm using ASP.NET MVC 5 and I'm cancelling logout in an overridden Controller.OnActionExecuted() method.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery
Rectangle 27 3

I needed to automatically log the user out when the browser or tab closes, but not when the user navigates to other links. I also did not want a confirmation prompt shown when that happens. After struggling with this for a while, especially with IE and Edge, here's what I ended doing (checked working with IE 11, Edge, Chrome, and Firefox) after basing off the approach by this answer.

First, start a countdown timer on the server in the beforeunload event handler in JS. The ajax calls need to be synchronous for IE and Edge to work properly. You also need to use return; to prevent the confirmation dialog from showing like this:

window.addEventListener("beforeunload", function (e) {        
      $.ajax({
          type: "POST",
          url: startTimerUrl,
          async: false           
      });
      return;
    });

Starting the timer sets the cancelLogout flag to false. If the user refreshes the page or navigates to another internal link, the cancelLogout flag on the server is set to true. Once the timer event elapses, it checks the cancelLogout flag to see if the logout event has been cancelled. If the timer has been cancelled, then it would stop the timer. If the browser or tab was closed, then the cancelLogout flag would remain false and the event handler would log the user out.

Implementation note: I'm using ASP.NET MVC 5 and I'm cancelling logout in an overridden Controller.OnActionExecuted() method.

javascript - Detect browser or tab closing - Stack Overflow

javascript jquery