The Stack Exchange network, GMail, Grooveshark, Yahoo! Mail, and Hotmail use the onbe
I think you could accomplish this with a timer (setInterval
) that starts in the onbeforeunload
callback. Javascript execution will be paused while the confirm dialog is up, then if the user cancels out the timed function could reset the alreadyPrompted
variable back to false, and clear the interval.
Just an idea.
Ok I did a quick test based on your comment.
<span id="counter">0</span>
window.onbeforeunload = function () {
setInterval(function () { $('#counter').html(++counter); }, 1);
return "are you sure?";
}
window.onunload = function () { alert($('#counter').html()) };
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
var promptBeforeLeaving = true,
alreadPrompted = false,
timeoutID = 0,
reset = function () {
alreadPrompted = false;
timeoutID = 0;
};
window.onbeforeunload = function () {
if (promptBeforeLeaving && !alreadPrompted) {
alreadPrompted = true;
timeoutID = setTimeout(reset, 100);
return "Changes have been made to this page.";
}
};
window.onunload = function () {
clearTimeout(timeoutID);
};
I have encapsulated the answers from above in an easy to use function:
function registerUnload(msg, onunloadFunc) {
var alreadPrompted = false,
timeoutID = 0,
reset = function() {
alreadPrompted = false;
timeoutID = 0;
};
if (msg || onunloadFunc) { // register
window.onbeforeunload = function() {
if (msg && !alreadPrompted) {
alreadPrompted = true;
timeoutID = setTimeout(reset, 100);
return msg;
}
};
window.onunload = function() {
clearTimeout(timeoutID);
if (onunloadFunc) onunloadFunc();
};
} else { // unregister
window.onbeforeunload = null;
window.onunload = null;
}
}
To register use:
registerUnload("Leaving page", function() { /* unload work */ });
To unregister use:
registerUnload();
Hope this helps ..