Just because you don't see use for a feature doesn't mean it isn't useful.
The Stack Exchange network, GMail, Grooveshark, Yahoo! Mail, and Hotmail use the onbeforeunload prompt to prevent/warn users that they are leaving a page after they have begun editing something. Oh yah, nearly every single desktop program that accepts saveable user-input data utilizes this prompt-user-before-leaving UX pattern.
I have a function which behaves similarly to this one:
window.onbeforeunload = function(){
// only prompt if the flag has been set...
if(promptBeforeLeaving === true){
return "Are you sure you want to leave this page?";
}
}
When a user attempts navigates away from the page the browser presents them with the option to leave or stay on the page. If the user selects the "Leave this page option" and then they quickly click on a link again before the page unloads completely the dialog fires again.
Are there any foolproof solutions to this problem?
Note: The following NOT the solution:
var alreadyPrompted = false;
window.onbeforeunload = function(){
// only prompt if the flag has been set...
if(promptBeforeLeaving === true && alreadyPrompted === false){
alreadyPrompted = true;
return "Are you sure you want to leave this page?";
}
}
because the user might select the "Stay on the page" option which would cause future onbeforeunload
s to stop working.
Best Solution
I think you could accomplish this with a timer (
setInterval
) that starts in theonbeforeunload
callback. Javascript execution will be paused while the confirm dialog is up, then if the user cancels out the timed function could reset thealreadyPrompted
variable back to false, and clear the interval.Just an idea.
Ok I did a quick test based on your comment.
In between the two callbacks
#counter
never got higher than 2 (ms). It seems like using these two callbacks in conjunction gives you what you need.EDIT - answer to comment:
Close. This is what i was thinking