在我的 rails 应用程序中,我想跟踪单个用户在站点上花费的总时间。我对此进行了研究,但无法获得完美的解决方案。
这怎么可能。
问问题
8885 次
3 回答
7
类似的东西?
var time,timeSite;
window.onload=function(){
time=new Date();
}
window.onbeforeunload=function(){
timeSite=new Date()-time;
window.localStorage['timeSite']=timeSite;
//store it with whatever serverside language.
}
如果你想要更多添加window.onblur
此代码有效.. ajax 也可以工作...
在极端解决方案中将其存储在本地存储中(如示例中),然后在下次登录时执行 ajax。
这可以为您提供以秒为单位的确切时间...
如果您想要大约时间并且对于没有本地存储的用户,请每 5 分钟添加一个 setTimeout
如果 ajax 和 localstorage 不起作用,则更新时间已过。
这是一个 ajax 调用,用于在 onbeforeunload 函数内部进行测试。
railsurl
随心所欲地改变。
var x=new XMLHttpRequest;x.open('get','railsurl?time='+timeSite);x.send();
正如@Yiğitcan Uçum 提到的那样..
为什么不直接使用服务器端会话来开始和结束在网站上花费的时间?
于 2014-01-07T13:27:02.267 回答
3
尝试这个:
var time,timeSite;
window.onload = function(){
time = new Date();
}
$(window).unload(function () {
timeSite = new Date() - time;
$.ajax({
type: 'GET',
async: false,
data: {timespent: timeSite},
url: '/url/to/rails.com'
});
});
于 2014-01-07T13:34:39.943 回答
0
jquery unload ()
事件处理程序可以用来处理这种情况,
例子 :
创建一个服务器端脚本,比如 track.php 以将所有收集到的跟踪详细信息保存到数据库中。
/* Assuming you are tracking authenticated users the */
在 Javascript 中:
var loggedInAt;
var loggedOutAt;
var userId = getUserId ();
function getUserId () {
return userId; // Define a mathod for getting the user if from a cookie or any local variables.
}
function getTotalTimeSpent() {
return (loggedOutAt - loggedInAt);
}
$(document).ready(function() {
loggedInAt = Date.getTime(); // get the start time when the user logged in
$(window).unload(function() {
loggedOutAt = Date.getTime();
totalTimeSpent = getTotalTimeSpent(loggedOutAt, loggedInAt);
$.ajax({
url: "www.yoursite.com/track.php",
method:post,
data: {'TotalTimeSpent': totalTimeSpent, 'UserId' : userId}
})
});
}
在 tracking.php 中:
获取变量$_REQUEST['TotalTimeSpent'] & $_REQUEST['UserId']
并进行插入查询以将信息传递到数据库中。
谢谢。
于 2014-01-07T13:37:53.913 回答