I have to prompt a user when he/she tries to exit the browser window. For example, when you go to GMail and you start posing a new message, and then try to close it before saving anything, GMail will give you a popup saying something like:
Do you really want to exit this page?
and then you have a choice of either leaving the page or staying on it. So what I am interested in is how they did it and what trick they used (if any) when the user presses Stay on this page
.
I have to prompt a user when he/she tries to exit the browser window. For example, when you go to GMail and you start posing a new message, and then try to close it before saving anything, GMail will give you a popup saying something like:
Do you really want to exit this page?
and then you have a choice of either leaving the page or staying on it. So what I am interested in is how they did it and what trick they used (if any) when the user presses Stay on this page
.
- 4 I just want to say, this can be annoying for some users. Do you really need it? Couldn't you save the info (somewhere), without having to do this? – Mateen Ulhaq Commented Jan 26, 2011 at 19:45
- Please don't do this. Signed, all internet users. – theflowersoftime Commented Mar 20, 2014 at 17:27
2 Answers
Reset to default 7To avoid annoying users, you would probably want to have the state to be changeable, depending on if an operation is running. Something like this:
window.beforeunload = function(){
if(isPerformingOperation) {
return 'Are you sure you want to leave?';
}
}
Set isPerformingOperation
to true when you want to prompt them, and turn it off when you are done.
Bind a function to onbeforeunload
.
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Should work in all browsers (tested in IE 8, FF 3.6, Chrome 9).
Or with jQuery:
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});