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.