Reputation: 43788
Does anyone know any way that I can use javascript to check when the browser window is closed and pop-up a confirmation dialog to ask whether the user is confirm to exit the browser or change his mind to stay?
Upvotes: 19
Views: 62229
Reputation: 5512
The documentation here encourages listening to the onbeforeunload
event and/or adding an event listener on window
.
window.addEventListener('beforeunload', function(e) {}, false);
You can also just populate the .onunload
or .onbeforeunload
properties of window
with a function or a function reference.
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.
Upvotes: 2
Reputation: 723
This works too, unless for IE8
$(window).bind('beforeunload', function (e) {
// code to execute when browser is closed
e.$.post("func.php", { action: 'action', id_userMsg: '<?php echo $id_user; ?>' });
});
Upvotes: 1
Reputation: 19
This worked for me:
function closeWin(){
var exit = confirm("Do you want to leave this window?");
if(exit==true){
//do something before closing;
}
}
body onbeforeunload="closeWin()"
Upvotes: 1
Reputation: 45422
window.onbeforeunload = function (e) {
var e = e || window.event;
//IE & Firefox
if (e) {
e.returnValue = 'Are you sure?';
}
// For Safari
return 'Are you sure?';
};
https://developer.mozilla.org/en/DOM/window.onbeforeunload
Upvotes: 27
Reputation: 50369
If the browser remains running after the page is closed, and if the browser processes the "onbeforeunload" event of the body element (sometimes it's disabled), and if the browser allows popup windows or mesage boxes and the ability to return false from that event to prevent the page change, then it's possible.
For an example, start typing a comment on any stackoverflow page with Javascript enabled and then navigate away from that page.
Upvotes: 1