Prompt for confirmation when leaving a page

Sometimes users leave a web page without clicking on a save button to save the changes they made to a form.
In this case, it can be useful to show a confirmation popup and ask them if they really want to leave the page without saving.
To achieve that, embed the following Javascript snippet (tested with IE9 and Firefox 5):

<script type="text/javascript">
window.onbeforeunload = function(){
	var message = 'There are unsaved changes. Are you sure that you want to leave this site?';
		return message;

The code above registers for the onBeforeUnload event, which fires when the user leaves the site, e.g. by

  • clicking on a link
  • entering a different URL in the browser
  • closing the browser window

You have to implement the checkForUnsavedFormChanges() function with your custom code to check for form changes.

When using the Dojo Toolkit, you can easily check for form changes using the dojo.formToObject(formNode: DOMNode|String); function. It will create a snapshot of a form. When the form is loaded, create a snapshot and compare this original snapshot with a new snapshot in the checkForUnsavedFormChanges() function.

Short URL for this post:
This entry was posted in Java Web Frameworks and tagged , , . Bookmark the permalink.

Leave a Reply

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