Warning the user before leaving the page

Warning the user before leaving the page !!!

Difficulty Level : Intermediate

You might have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.
Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.

Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.

Following is the code :

var shouldsubmit = false; // Represent the button should ask for confirmation or not.
window.onbeforeunload = confirmUnloading;



// Funcion called before unloading of the page.
function confirmUnloading()
{
        if (!shouldsubmit)
        {
                return "If you have any unsaved data in the current page, it will be lost.";
         }
  }



Here is a known issue  :

For IE, the warning will prompt twice in case of link button. Reason is that HTML code for ASP.NET link button is like
So it fires once for doPostBack event and twice for real unloading of the page.

Work Around :

You can set another flag and set like the following.

var shouldsubmit = false; // Represent the button should ask for confirmation or not.
var isFiredTwice = false;
window.onbeforeunload = confirmUnloading;

// Funcion called before unloading of the page.
function confirmUnloading()
{
        // Check for both the condition to check whether some change occur in the page or not.
       if (!shouldsubmit)
        {
         if (navigator.appName == "Microsoft Internet Explorer") // For IE
                 {
                     if (!isFiredTwice)
                      {
                       event.returnValue = "If you have any unsaved data in the current page, it will be lost."
                       isFiredTwice = true;
                       setTimeout("isFiredTwice = false;", 0)
                      }
                 }
                 else
                 {
                   // For FF
                 return "If you have any unsaved data in the current page, it will be lost.";
                 }
         }
}

Again you can add one more flag to keep track of any changes in the form elements to fire the warning to prevent loosing unsaved data.

Hope this helps you.
Happy Coding !!!

150 150 Burnignorance | Where Minds Meet And Sparks Fly!