So... how to get user action then?
You actually can't, directly. The browser takes charge of showing the confirmation, and either continuing the navigation if OK, or doing nothing if Cancel. You don't get to find out whether the user clicked OK until you get the final unload
, by which point it's too late.
One strategy is to guess that, if the user is still around on the page a short while after the beforeunload
, they probably clicked Cancel:
var redirecting= false;
window.onbeforeunload = function() {
if (redirecting) return;
setTimeout(function() {
setTimeout(function() {
redirecting= true;
location.href= 'http://www.example.com/';
}, 2000);
}, 0);
return 'Boo hoo, please stay with me';
};
(The redirecting
flag is to stop our own navigation also causing a beforeunload
warning; the double-timeout is to ensure that the timeout occurs one second after the confirmation box is closed, rather than a second after it has opened.)
Unfortunately this is still highly unreliable, as it will perform the redirect even if the user clicked OK, but the page to which they're navigating is taking more than two seconds to start loading.
Another way would be to always return nothing from beforeunload
prompt, and then set up your own explicit confirm()
on a 0-timeout. But this is unreliable cross-browser, as understandably browsers don't really want to let pages do potentially obnoxious stuff like this. It kind of works on IE and almost works on Firefox, as long as you break the back/forward cache (as this hides the page before the confirm can happen).
In summary there's not really a good solution. What's the use case for redirecting the user? Perhaps you could try replacing the content of the current page rather than doing a redirect?