In a web app I'm working on, I'm capturing onBeforeUnload to ask the user whether he really wants to exit.
Now, if he decides to stay, there are a number of things I'd like to do. What I'm trying to figure out is that he actually chose to stay.
I can of course declare a SetTimeout for "x" seconds, and if that fires, then it would mean the user is still there (because we didn't get unloaded). The problem is that the user can take any time to decide whether to stay or not...
I was first hoping that while the dialog was showing, SetTimeout calls would not fire, so I could set a timeout for a short time and it'd only fire if the user chose to stay. However, timeouts do fire while the dialog is shown, so that doesn't work.
Another idea I tried is capturing mouseMoves on the window/document. While the dialog is shown, mouseMoves indeed don't fire, except for one weird exception that really applies to my case, so that won't work either.
Can anyone think of other way to do this?
Thanks!
(In case you're curious, the reason capturing mouseMove doesn't work is that I have an IFrame in my page, containing a site from another domain. If at the time of unloading the page, the focus is within the IFrame, while the dialog shows, then I get the MouseMove event firing ONCE when the mouse moves from inside the IFrame to the outside (at least in Firefox). That's probably a bug, but still, it's very likely that'll happen in our case, so I can't use this method).
What I ended up doing was hooking into the click event for my document, and once I received a click I considered the user had stayed.
It's not a good solution, in most cases (if you are a DiggBar) you'll have lots of false negatives (people will have stayed and you'll never know it), but in our case it made perfect sense, because people interact heavily with our site, not only with the framed sites.
Esentially, my code does this...
function OnBeforeUnload() {
Event.observe(document, "click", UserStayed);
if (IConsiderTheIFrameMightBeTryingToPopOut) {
return "The site is trying to escape. Do you want to stay?";
}
}
function UserStayed() {
Event.stopObserving(document, "click", UserStayed);
// New we know the user is still with us for sure.
}