Rectangle 27 0

javascript Trying to detect browser close event?


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

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

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

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.

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

did you see any errors in console?

Note
Rectangle 27 0

javascript Trying to detect browser close event?


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

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

Doesnt work in Firefox v33

Fiddle url is not working anymore.please check and update

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

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

Note
Rectangle 27 0

javascript Trying to detect browser close event?


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

Note
Rectangle 27 0

javascript Trying to detect browser close event?


$(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();
});
Cannot read property 'toUpperCase' of undefined

the mouse will be out of the window, pointing out at the close button ('X')

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

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?

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.

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

Note
Rectangle 27 0

javascript Trying to detect browser close event?


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

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

Note
Rectangle 27 0

javascript Trying to detect browser close event?


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

Response to question in comment

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

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

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

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

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.

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

Note
Rectangle 27 0

javascript Trying to detect browser close event?


<!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.. And make changes in the data base also.....

Note