Managing window.onbeforeunload in Javascript

I struggled with this quite a bit because there is a lot of information on the web that is conflicting. I wanted a way to tell the user that they had unsaved changes when they tried to leave an editing page but not get the warning when they hit the save button. This seems like a logical user experience to me!  The trick I found was to create a flag that the event handler checks to know whether you are in the middle of a save or not. To be slightly more generic, I called it showUnsavedChangesWarning and defaulted it to true. Here is the code I ended up with:

top.showUnsavedChangesWarning = true;
window.onbeforeunload = function (event)
if (top.showUnsavedChangesWarning) {
var e = event || window.event;

// If we have unsaved changes, tell the browser to show a confirmation window
var message = null;
var document = Editor.getActiveDocument();
if (document != null && document.hasUnsavedChanges()) {
message = 'You have not saved changes in your file.';
// Firefox 4 doesn't let you specify the text but does popup a warning.
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = message;
// For Safari
return message;

// otherwise just fall through and return nothing

You won’t have the Editor object unless you’re also working with Xopus but you get the idea. The interesting details here are:

  1. Don’t return anything if you want the browser to just continue on. Some sites recommended null, some the empty string. The only thing that works consistently for me is not returning anything.
  2. Safari seems to have different handling from everyone else
  3. Firefox4 doesn’t let you display a custom message anymore. You can of course display your own confirm dialogue but they’ve removed the ability for you to stick custom text into a Firefox application dialogue. I think this is a good decision.

Hopefully this helps you too.