开发者

Get User Spent Time onunload In Asp.Net and javascript

开发者 https://www.devze.com 2023-01-10 18:59 出处:网络
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

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. 开发者_Go百科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();
}

c#

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号