I'm sure we've all done it at some point, spent ages on a web page updating some information only to lose the changes for some reason. Sometimes its not your fault i.e. the server goes down whilst you're in the middle of making a change but sometimes your just to quick for your own good and navigate away from a page without saving the change. whatever happens it can be extremely frustrating!
A recent client has asked me to warn users when they are about to navigate away from a page before saving their changes. They wanted this warning to appear if the users clicks a link within the application or uses the browser back button or closes the window. One easy solution to this is the window.onbeforeunload javascript event.
This event will fire whenever the user leaves the page. You can also pass the event a custom message to display in the warning box. To wire this into your page simply add the ProjectDataChanged() function call to the onchange event of any controls that can alter data on the page.
function ProjectDataChanged()
{
window.onbeforeunload = ShowProjectDataChangedWarning;
}
function ShowProjectDataChangedWarning()
{
return 'Navigating away from this page will cause you
to lose any changes you have made. Please use the publish
button(s) at the bottom of the page to save your changes.';
}
To stop the message from appearing (when the user successfully saves) call the CancelCheck function.
function CancelCheck()
{
window.onbeforeunload = '';
}
Hope this helps..