测量用户在网站访问期间花费的时间

时间:2016-12-23 19:30:49

标签: javascript php jquery ajax timer

我正在尝试使用PHP和Javascript以及MAMP在本地构建一个网站。

我正在寻找的是在网站的每个页面上放置一个计时器,该计时器计算用户在整个网站上花费的时间。即使用户在页面之间切换,计时器仍将继续。我找到的解决方案只显示每页上花费的时间,当我再次重新加载同一页时,计时器从零开始重新启动。

这是我做过的计时器的Javascript:

window.onload=function(){
 time=0;
}
window.onbeforeunload=function(){
 timeSite = new Date()-time;
 window.localStorage['timeSite']=timeSite;
}

我到处寻找解决方案,但没有运气,如果有人知道怎么做,请告诉我。

2 个答案:

答案 0 :(得分:1)

这是一个有效的例子。与Peter的答案不同,当用户关闭窗口/标签时,它将停止计数。

var timer;
var timerStart;
var timeSpentOnSite = getTimeSpentOnSite();

function getTimeSpentOnSite(){
    timeSpentOnSite = parseInt(localStorage.getItem('timeSpentOnSite'));
    timeSpentOnSite = isNaN(timeSpentOnSite) ? 0 : timeSpentOnSite;
    return timeSpentOnSite;
}

function startCounting(){
    timerStart = Date.now();
    timer = setInterval(function(){
        timeSpentOnSite = getTimeSpentOnSite()+(Date.now()-timerStart);
        localStorage.setItem('timeSpentOnSite',timeSpentOnSite);
        timerStart = parseInt(Date.now());
        // Convert to seconds
        console.log(parseInt(timeSpentOnSite/1000));
    },1000);
}
startCounting();

如果要在窗口/选项卡处于非活动状态时停止计时器,请添加以下代码:

var stopCountingWhenWindowIsInactive = true; 

if( stopCountingWhenWindowIsInactive ){

    if( typeof document.hidden !== "undefined" ){
        var hidden = "hidden", 
        visibilityChange = "visibilitychange", 
        visibilityState = "visibilityState";
    }else if ( typeof document.msHidden !== "undefined" ){
        var hidden = "msHidden", 
        visibilityChange = "msvisibilitychange", 
        visibilityState = "msVisibilityState";
    }
    var documentIsHidden = document[hidden];

    document.addEventListener(visibilityChange, function() {
        if(documentIsHidden != document[hidden]) {
            if( document[hidden] ){
                // Window is inactive
                clearInterval(timer);
            }else{
                // Window is active
                startCounting();
            }
            documentIsHidden = document[hidden];
        }
    });
}

JSFiddle

答案 1 :(得分:0)

使用localStorage可能不是您需要的最佳选择。但sessionStoragelocalStorage最合适。请注意,在打开新标签时,sessionStorage会解析为新会话,因此使用localStorage与仅使用sessionStorage并且用户打开新标签的事实有关并行访问您的网站将解析为该浏览器选项卡的新单独会话,并从头开始计算timeOnSite。在以下示例中,尝试避免并计算确切的timeOnSite

  

sessionStorage属性允许您访问会话存储   当前来源的对象。 sessionStorage类似于   Window.localStorage,唯一的区别是存储数据时   localStorage没有过期设置,sessionStorage中存储的数据会获得   页面会话结束时清除。页面会话持续时间很长   当浏览器打开并在页面重新加载和恢复时幸存。   在新选项卡或窗口中打开页面将导致新会话   已启动,这与会话cookie的工作方式不同。

function myTimer() {
if(!sessionStorage.getItem('firstVisitTime')) {
   var myDate = Date.now();
   if(!localStorage.getItem('timeOnSite')) {
   sessionStorage.setItem('firstVisitTime',myDate);
   } else {
   if(localStorage.getItem('tabsCount') && parseInt(localStorage.getItem('tabsCount'))>1){
   sessionStorage.setItem('firstVisitTime',myDate-parseInt(localStorage.getItem('timeOnSite'))); 
   } else {
   sessionStorage.setItem('firstVisitTime',myDate);
   } 
}
}
var myInterval = setInterval(function(){  
   var time = Date.now()-parseInt(sessionStorage.getItem('firstVisitTime'));
   localStorage.setItem('timeOnSite',time); 
   document.getElementById("output").innerHTML = (time/1000)+' seconds have passed since first visit';
}, 1000);
return myInterval;
}    
window.onbeforeunload=function() {
console.log('Document onbeforeunload state.');
clearInterval(timer);
};
window.onunload=function() {
var time = Date.now();
localStorage.setItem('timeLeftSite',time);
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))-1);
console.log('Document onunload state.');
};
if (document.readyState == "complete") {
if(localStorage.getItem("tabsCount")){
localStorage.setItem("tabsCount",parseInt(localStorage.getItem("tabsCount"))+1);
var timer = myTimer();
} else {
localStorage.setItem("tabsCount",1);
}
   console.log("Document complete state.");
}

工作fiddle

如果您需要服务器端解决方案,请设置$_SESSION['timeOnSite']变量并相应更新每个页面导航。