IE OnBeforeUnload Fun
Was debugging something today when I made a discovery. Using Internet Explorer’s onbeforeunload event handler, you can automatically pop up a confirmation window asking the user to continue navigating away or stay on the page with ever using confirm(). All you have to do is set your message in the window.event.returnValue property, and the browser handles it automatically. For instance:
window.onbeforeunload = function () {
window.event.returnValue = "All your work will be lost.";
}
This results in a window being popped up that shows this text as well as, “Are you sure you want to navigate away from this page?” before it and “Press OK to continue or Cancel to stay on the current page.” Pretty cool undocumented feature.
Disclaimer: Any viewpoints and opinions expressed in this article are those of Nicholas C. Zakas and do not, in any way, reflect those of my employer, my colleagues, Wrox Publishing, O'Reilly Publishing, or anyone else. I speak only for myself, not for them.
Both comments and pings are currently closed.




4 Comments
What’s even cooler is that it works in Firefox too! I’ve used this feature for one of my projects and is really helpful when used correctly. Let’s hope others don’t ruin it by asking, "Are you sure you want to navigate away from my really cool site?!?"
Kevin on March 1st, 2006 at 8:30 pm
Kevin – how do you do it in Firefox? I know the event fires, but how about the automatic popping up window?
Nicholas C. Zakas on March 1st, 2006 at 8:57 pm
In Firefox, I just went like this:
window.onbeforeunload = function() {return("This will take you back to the login page.");}
(Excuse the poor style.)
However, what if we don’t actually *want* the Firefox before and after text? Especially since it seems incorrect sometimes–this event also fires when the user clicks ‘reload’, so they’re not navigating away from the page per se (though I understand why this is done.)
Kev
Kev (a different Kev) on June 12th, 2006 at 3:23 pm
I guess there’s not much one can do about the text…
http://www.opendarwin.org/pipermail/webkit-unassigned/2006-January.txt
Kev
Kev on June 12th, 2006 at 3:52 pm
Comments are automatically closed after 14 days.