In the past as we have moved more applications to the browser, there are some users who still struggle with the change from a desktop application to the browser. One main change is that the browser applications don’t always prompt for saving data as the user closes the browser or navigates away from the page. Changes are made, and the changes are lost as they navigate away from the page without saving. How do you ensure that changes to the data are saved before the user navigates away or closes the browser?

The javascript window.onbeforeunload event can help with this.

window.onbeforeunload = some_function

Your code can be as simple as the above, but I would recommend a few additions, e.g. checking to see if the user has made any changes before you throw up a confirmation prompt. It is always annoying to make no changes, but still be prompted to save before navigating away. In order to track if changes have been made, here is a simple javascript tracking example. Of course, your pages may be much more complicated, but this will illustrate one approach.


var values = new Array('', '', '', '', '', '');
var needToConfirm = true;

window.onbeforeunload = confirmExit;
function confirmExit()
{
if (needToConfirm)
{
// check to see if any changes to the data entry fields have been made
for (var i = 0; i < values.length; i++)
{
var elem = document.getElementById(ids[i]);
if (elem)
if ((elem.type == 'checkbox' || elem.type == 'radio')
&& values[i] != elem.checked)
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
else if (!(elem.type == 'checkbox' || elem.type == 'radio') &&
elem.value != values[i])
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}

// no changes - return nothing
}
}

Enjoy this bit of code, but be careful not to over use it. It can be annoying. :)

Posted: August 3, 2009, 8:20 am by Brian Radford

Respond to this post or Trackback Link

So far none to this article

  1. So far no posts

Add your own post

You must log in in order to be able to contribute.



RSS 2.0-Feed for the comments to this article.