我需要获取每个用户在页面上花费的时间并将该信息插入数据库。
当页面加载时,我将开始时间分配给 JavaScript 值。在 body 的 onunload 函数上,我计算开始时间和结束时间之间的时间差,以便我可以将其插入数据库。
我使用脚本管理器并将 EnablePageMethods 设置为 true。在我调用 onunload 的 javascript 函数中,我使用 pagemethods 调用 Web 方法。
它在 Firefox 中似乎运行良好。但是在 Chrome 和 IE 中它不起作用。
你们有什么想法吗,因为我真的失去了它。提前致谢。
脚本管理器代码是:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
js代码是这样的:
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# 代码是这样的:
[System.Web.Services.WebMethod]
public static void ClosePage(int milliseconds)
{
try{
// Insert millisecond to database...
}
catch
{ }
}
最佳答案
如果我需要这个,我会实现 js 时钟,它会向服务器报告用户是否在线。具有相同 session ID 的第一条和最后一条记录将指示用户在您的网站上花费的时间。
Js 类似:
$.post("/KeepSessionAlive.ashx", null, function() {
LastConnectionTime=new Date();
}
c#
public void ProcessRequest(HttpContext context) {
context.Session["KeepSessionAlive"] = DateTime.Now;
//etc
}
关于c# - 获取用户在 Asp.Net 和 javascript 中花费的 onunload 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449600/