Saturday, 22 October 2011

Calling server method when closing the browser

This post provides implementation for calling server method when closing the browser. This example works fine with Internet Explorer.

The requirement of this example is defined below.
  1. When the user closing the browser, it should call the server method for storing the time the page open and close.
  2. In other example, when the user closing the browser it should confirm from the user whether they want to close the browser. If yes, it should call the server method to save the time the browser open and close. If not, stay in the page without doing anytime.

There are two example provided below. One is to achieve the first requirement and the other one is to achieve the second requirement.

Step 1: Creating a table (BrowserLifeTime) in SQL Server for storing the page open and close time.
CREATE TABLE [dbo].[BrowserLifeTime](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [ToDateTime] [datetime] NOT NULL,
 [FromDateTime] [datetime] NOT NULL,
 [Name] [varchar](50) NOT NULL
) ON [PRIMARY]
GO

Step 2: To call a server method, I am adding a WebService file (UploadService.asmx). The file is used to define a method which can call from server when closing the browser. (Note: There are lots of ways to call the server method from server, one is using WebService. You can use any other concepts such as XML HTTP AJAX, GenericHandler, WebServices etc.,)
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class UnloadService : System.Web.Services.WebService
{
    [WebMethod]
    public void UpdateBrowserLife(string strStartDateTime, string strEndDateTime)
    {
        SqlConnection connection = null;
        try
        {
            connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ToString());
            connection.Open();

            SqlCommand command = new SqlCommand("insert into BrowserLifeTime (ToDateTime, FromDateTime, Name) values ('" + strStartDateTime + "', '" + strEndDateTime + "', SYSTEM_USER)", connection);
            command.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            connection.Close();
        }
    }
}

Step 3: Below script for registering WebService proxy.
<asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
        <asp:ServiceReference Path="~/UnloadService.asmx" />
    </Services>
</asp:ScriptManager>
Step 4: Below Javascript code is to implement the first requirement – call server method when closing browser without any confirmation.
<script type="text/javascript" language="javascript">
    var startDateTime = new Date();
    var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    startDateTime = startDateTime.getDate() + "-" + m_names[startDateTime.getMonth()] + "-" + startDateTime.getFullYear() + " " + startDateTime.getHours() + ":" + startDateTime.getMinutes() + ":" + startDateTime.getSeconds();

    var browserName = navigator.appName; // Get the Browser Name

    if (browserName == "Microsoft Internet Explorer") {
        window.onload = HandleOnClose;
    }
    else {
        window.onbeforeunload = HandleOnClose;
    } 

    function HandleOnClose() {
        var endDateTime = new Date();
        endDateTime = endDateTime.getDate() + "-" + m_names[endDateTime.getMonth()] + "-" + endDateTime.getFullYear() + " " + endDateTime.getHours() + ":" + endDateTime.getMinutes() + ":" + endDateTime.getSeconds();

        CallServerOnUnload.UnloadService.UpdateBrowserLife(startDateTime, endDateTime);
        return true;
    }
</script>
Note: I tried in this requirement for implementing for other browsers (Firefox, Chrome, Opera). But seems not working. Below example implements only for IE.

Below Javascript code is to achieve the second requirement – calling server method once the confirmation from the user.
<script type="text/javascript" language="javascript">
    // Works in IE only.
    var startDateTime = new Date();
    var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    startDateTime = startDateTime.getDate() + "-" + m_names[startDateTime.getMonth()] + "-" + startDateTime.getFullYear() + " " + startDateTime.getHours() + ":" + startDateTime.getMinutes() + ":" + startDateTime.getSeconds();
    
    window.onbeforeunload = CallBeforeUnload;
    window.onunload = HandleOnClose;
    function CallBeforeUnload() {
        return "Are you sure you really want to close?";
    }
    function HandleOnClose() {
        var endDateTime = new Date();
        endDateTime = endDateTime.getDate() + "-" + m_names[endDateTime.getMonth()] + "-" + endDateTime.getFullYear() + " " + endDateTime.getHours() + ":" + endDateTime.getMinutes() + ":" + endDateTime.getSeconds();
        CallServerOnUnload.UnloadService.UpdateBrowserLife(startDateTime, endDateTime);
    }
</script>
Download the source code in C# here and in VB here.

The output looks below


1 Response to “Calling server method when closing the browser”

  • Anonymous says:
    5 July 2012 at 07:30

    nice and really different posts by dotnettwitter.
    Thank you dotnettwitter.
    Gauri

Post a Comment