Tutorial :Get User Spent Time onunload In Asp.Net and javascript


I need to get the time every user spent on the page and insert that information to database.

When the page loads I assign a start time to a javascript value. on body's onunload function I calculate the time difference between the start time and end time so that I can insert it to database.

I use script manager and EnablePageMethods is set to true. And in the javascript function that I call onunload I call a web method by using pagemethods.

It seems to work fine in Firefox. However in Chrome and in IE it does not work.

Does any of you have any idea, because I am really loosing it. Thanks in advance.

The Script Manager code is :

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">                          </asp:ScriptManager>  

The js code is something like that :

function ExitPage() {          try {          var leavingTime = new Date();          alert("entering: " + enteringTime);          alert("exiting: " + leavingTime);          var diff = leavingTime - enteringTime;          alert("diff: " + diff);          alert(window.location);            }          catch (Err) {              alert("Before error:" + Err.Description);          }            try {                alert("Before PageMethods Call");                PageMethods.set_path('SomePage.aspx');              PageMethods.ClosePage(diff,onSuccess,onFail);          }          catch (Err) {              alert("Error In PageMethods Block:" + Err.Description);          }            alert("Before Return");          return false;        }        function onSuccess() {          alert("Success");      }        function onFail() {          alert("Fail");      }  

C# Code is something like that :

[System.Web.Services.WebMethod]          public static void ClosePage(int milliseconds)          {              try{                  // Insert millisecond to database...              }              catch              { }          }  


If I would need this I would implement js clock which would report to server that user is on line. The first and the last record with the same session id would indicate time user spend on your site.

Js something like:

$.post("/KeepSessionAlive.ashx", null, function() {     LastConnectionTime=new Date();  }  


public void ProcessRequest(HttpContext context) {     context.Session["KeepSessionAlive"] = DateTime.Now;     //etc  }  


One of the best solution I could find to this problem is using jQuery for the client side and the asp.net web services for the backend. jQuery works like a charm since in most cases it works in different browsers.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »