I don't have an actual use case for this, but I'm curious, whether there is a way to react (callback), if a user clicks on "stay on this page" when window.onbeforeunload was triggered.
http://jsfiddle.net/rWHU9/
function warning(){ if(true){ console.log('leaving'); return "You are leaving the page"; } } window.onbeforeunload = warning;
Cancelable: The beforeunload event can be canceled by user interaction: // by https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload#Example window. addEventListener("beforeunload", function(event) { event. preventDefault(); // Cancel the event as stated by the standard.
The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page.
onbeforeunload = function () {/**/} will override any existing handlers and replace it with your own. window. addEventListener("beforeunload", function () {/**/}); will add a new handler.
There is no callback for staying on the page, but there is one for leaving the page, window.unload
.
Try setting a timeout in beforeunload
, then clear it in unload. If you stay, the timeout will run, otherwise it'll be cleared.
var timeout; function warning() { timeout = setTimeout(function() { alert('You stayed'); }, 1000); return "You are leaving the page"; } function noTimeout() { clearTimeout(timeout); } window.onbeforeunload = warning; window.unload = noTimeout;
DEMO: http://jsfiddle.net/aPwfz/1/
Short answer: No, there is no callback or any direct way to intercept the "stay on this page" event, yet.
However, you can cheat a little and create a construct like this:
function warning() { setTimeout(function() { setTimeout(function() { alert('user choosed to stay on this site: ' + location.href); }, 100); },1); return "You are leaving the page"; } window.onbeforeunload = warning;
Since the question is a modal dialog, the setTimeout
callback will not fire until you confirmed that modal box. But as you correctly assume now, this would also trigger if you click "leave this site". So this is tricky. To solve that, you would need to increase the setTimeout
to give the browser enough time to unload
the page.
Why there are two setTimeout()
's nested ? Well, the timer will "run" as soon as the modal dialog pops up. So we don't want to run that timer until the modal dialog was closed. As soon as that happens, our inner setTimeout
will launch and do something over time.
I think a realistiv value for most real-world scenarios is about 2.000
ms for the inner setTimeout
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With