Hack #33. Confirm Before Closing Modified Pages
Don't lose your changes in web forms when you accidentally close your browser window.
It's becoming more and more common for complex tasks to be performed on the Web. Of course, there is web-based email, and weblogging and wikis are also popular. Message boards are a great way to form a community, and there are many more online applications that are used every day by many people. One of the drawbacks, though, in not using a normal desktop program is losing that prompt, "Are you sure you wish to exit? You have unsaved work."
With Greasemonkey, we can restore this functionality and save the hassle caused by closing a window and losing your unsubmitted form data.
The Code
This script uses the power of the onbeforeunload event to catch the browser just before it moves off the page. When the page loads, the script finds all <textarea> elements and records the initial value of each one. Then, we register an onbeforeunload event handler to call our function that checks the current value of each <textarea>. If the current value differs from the previously recorded value, we display a dialog box to give the user the chance to save his work.
To make sure we don't interfere when the user actually submits the form, the script attaches an onsubmit event handler to all forms. This handler sets an internal flag to record that the user submitted the form and that we should not bother checking for unsubmitted data, since the user just submitted it!
Save ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access