Invoking Server Side code using ASP.NET AJAX Client Callback on Web browser close

If your ASP.NET web application creates temporary data for the each session, it needs to be deleted while user logs out. If you use InProc session mode, then you can handle Session_End event in the Global Application file(Global.asax) to clear the temporary files.

Suppose if you use other than InProc session mode[i.e., StateServer, SQLServer etc.,], then you have to write custom logic to delete the temporary files while user logs out.

Till now you everything is fine, if user logs out of the using Logout option in your web application. What if User closes the browser unintentionally? The temporary files remain undeleted!

Let us discuss a solution which handles the above problem using ASP.NET AJAX with JavaScript.  First of all we need to a notification, when user closes the browser. So let us create a JavaScript function, which notifies the Web browser close.

<script type="text/javascript">
        window.onbeforeunload = NotifyBrowserClose;
        function NotifyBrowserClose() {
            return "Are you sure to close the browser?";
        }
    </script>

The above code notifies the user, if he tries to close the browser.

NOTE: User gets notification even when he traverse to other page. So you need to use a Boolean variable to check whether  the user is traversing to other page or trying to close the browser!

Now we will create Server Side Code to delete the temporary files! Implement the ICallbackEventHandler interface to call Server Side code from Client code(JavaScript).

#region ICallbackEventHandler Members

        public string GetCallbackResult()
        {
            return "";
        }

        public void RaiseCallbackEvent(string eventArgument)
        {
            string      strTempLoc      =  Session["TempFilesDir"].ToString();
            string[]    strTempFiles    = null;

            try
            {
                if (!string.IsNullOrEmpty(strTempLoc) &&
                    Directory.Exists(strTempLoc))
                {
                    strTempFiles = Directory.GetFiles(strTempLoc);

                    //Delete all the files in the temp location
                    foreach (string strTempFile in strTempFiles)
                    {
                        File.Delete(strTempFile);
                    }

                    Directory.Delete(strTempLoc);
                }
            }
            catch (IOException)
            {

            }

        }

        #endregion

Now register the JavaScript functions to invoke the Server Side code.

protected void Page_Load(object sender, EventArgs e)
{
//Get the Client Call back event reference
            string strCallBackRef = Page.ClientScript.GetCallbackEventReference(this, "", "DeleteStatus", "");

            //Form the callback function which is invoked in the Client side
            string strCallBackScript = "function DeleteTempFiles()" + "{" + strCallBackRef + ";}";

            //Register
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                                                        "MyServerCall",
                                                        strCallBackScript,
                                                        true);
}//end: Page_Load function

Now invoke the function on Web browser close as shown below!

 <script type="text/javascript">

        window.onbeforeunload = NotifyBrowserClose;
        function NotifyBrowserClose() {
            //Server Side Code call back
             DeleteTempFiles();
        }

       //Client Call back
        function DeleteStatus(result) {
        }

    </script>

Hope it helps u…

Happy Web Programming!!!

5 Comments

  1. Show alert message to user when closing browser window
    Its basic need to alert a customer before closing browser. In vb.net we used to write the code in closing button but in asp.net we can’t do like that, so we go for JavaScript to make same alert like in vb.net. This alert will display whenever user try to close the browser or move to the next page alert will be shown…
    Below Code we have to write body tag on window before unload event call the script function..

    Script:

    var msg = “Are you sure you want to leave close this page?”;
    function ConfirmClose(e) {
    var evt = window.event ? event : e;
    if (evt == e) {
    if (!evt.clientY) {
    evt.returnValue = msg;
    }
    }
    else {
    if (evt.clientY < 0) {

    evt.returnValue = msg;
    }
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s