Prevent the loss of unsaved data with OnBeforeUnload

Sometime last year I learned about the onUnload event, which is available on the "window" object. Today I thought I could use it to prevent a user from leaving a web page if, for example, there is unsaved data that will be lost. I quickly realized that it would not work. The "onunload" event happens after the user has already "unloaded" the page. I needed an event that fired before the user action and naturally came upon, "onBeforeUnload."

The onBeforeUnload event is Microsoft specific and is not included in the W3C specification but fortunately seems to be a de facto standard in the modern web browsers. Support is in the latest versions of FireFox, Safari, Chrome and Internet Explorer. Below is a code example and screenshots of resulting dialog boxes in Safari and Google Chrome.

window.onbeforeunload = function() {
    return "There is unsaved data on this page.";
}

Safari Dialog
Safari

Chrome Dialog
Chrome

Safari's dialog default formatting is close to an exact match of all other browsers. Google Chromem however, displays a much smarter dialog. It didn't take much thought to realize that they did this for their web applications. If for example, you try to reload an unsaved e-mail in Gmail you will trigger an "onBeforeUnload" event.

To clear the beforeUnload event just set the value of it to null as follows:

window.onbeforeunload = null;

See the example.

Tags: