Archive for the ‘VB.Net Tutorial’ Category

Stopping a user from clicking the browser close button before a save action has happened.

Tuesday, October 13th, 2009

The JavaScript event “window.onbeforeunload” can be setup to process a JavaScript function prior to a web page unloading.  In this way a confirm message can be seen prior to a user losing un-saved data.   My example scenario would be any page that requires a large amount of user input and contains a single save button.  Way too often users enter plenty of text and forget to press a save button and then navigate away.  The window.onbeforeunload will be raised on the browser’s page back, page forward button or simply closing the page completely.   This event can be used as a last ditch effort to get the users to save before they potentially do something stupid.

Setting up the web page to monitor for the unloading event is simple.  Simply code the event in a JavaScript area (inline code) and have a new function name handy for executing your own custom message.  When the event is raised by the browser this new custom function will be triggered.  Additionally you may want to set up a global Boolean variable to decide if it is Okay to navigate away without getting an message.  i have named my custom function bunload() as seen below.

<script language="JavaScript">

    var strOkayToLeave = 'False';

    window.onbeforeunload = bunload;

</scipt>

Now that the event is being monitored due to the additional “window.onbeforeunload”, we need to code the confirming message as follows:

function bunload(){

    if ( strOkayToLeave != 'True') {

      mess = "You will lose all information provided\nduring navigation of this site";

      return mess;

  }

  return

}

Finally you will want to monitor the save button and set the strOkayToLeave = True.   This will allow your users to easily leave without getting prompted to save when they have already done so.   Thus you will set this true directly after a save and set it false whenever the TEXTAREA(s) or inputs have a onchange event.  For example: onchage=strOkayToleave=’False’.  This way you will remind your users to save after every change and not allow them to forget and simply close the browser.

You can only lead a horse to water but you can not make him drink.  The warning that your user’s will see is a Ok/Cancel dialog.  So they could press the OK button and still navigate away without saving but at least they were warned.

image