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