Warn the user before navigating away from a web page using JavaScript

Warn the user before navigating away from a web page using JavaScript

In rich client applications, it is easy to check to see if a document has been modified and react when the user closes the program or document. Not so easy with web pages.

For example, when you close Microsoft Word without saving, you get a warning and the option to save.

How can this be done with a web form?

My initial Google search found the answer “it’s not possible.” But this is not true, as Gmail prompts you before navigating away from the Compose Email screen (which has saved me lots of grief). 

I think Gmail uses some combination of the body onUnload event and rewriting/replacing the URL, but saving all data. OnUnload is triggered when the web page is unloaded, whether by navigating away or closing the browser window.

However, it is not possible to interrupt this event, so while you could create a popup, it wouldn’t be effective at stopping the close. IE has a non-standard onBeforeUnload event which, if the event has a non-null return value, displays a popup window with the return value as the body. The button has an OK and a Cancel. Cancel interrupts the onUnload event. 

This event is available in Firefox now also.

So here’s what I did:

In the head, I created a flag to store whether the user should be warned.

Now, in the body tag I added the onBeforeUnload event:

onbeforeUnload="if (transitionWarning) return 'You will lose all unsaved changes if you navigate away!  To save your changes, press the save button'"

And then on the submit button I disable the transition warning so the user is not prompted when saving the form.

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *