衡量用户在网站访问期间花费的时间 [英] Measure time spent by a user during a website visit
问题描述
我正在尝试使用PHP和Javascript以及MAMP在本地建立一个网站.
I'm trying to build a website locally using PHP and Javascript and MAMP.
我要寻找的是在网站的每个页面上放置一个计时器,该计时器计算用户在整个网站上所花费的时间.即使用户在页面之间切换,计时器仍将继续.我找到的解决方案仅显示在每个页面上花费的时间,当我重新加载同一页面时,计时器从零重新开始.
What I'm looking for is to put a timer on every page of the website and that timer counts the time spent by the user in the whole website. Even if the user switches between pages the timer will still continue. The solution I've found only shows the time spent on each page and when I reload the same page again the timer restart from zero.
这是我做的计时器的Javascript:
Here's the Javascript for the timer I did:
window.onload=function(){
time=0;
}
window.onbeforeunload=function(){
timeSite = new Date()-time;
window.localStorage['timeSite']=timeSite;
}
我到处都在寻找解决方案,但是没有运气,如果有人知道该怎么做,请告诉我.
I've search everywhere for the solution but with no luck, if anyone knows how to do this please let me know.
推荐答案
这是一个可行的示例.与Peter的答案不同,当用户关闭窗口/标签时,它将停止计数.
Here's a working example. Unlike Peter's answer, it will stop counting when the user closes the window/tab.
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();
如果要在窗口/选项卡处于非活动状态时停止计时器,请添加以下代码:
Add the code below if you want to stop the timer when the window/tab is inactive:
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];
}
});
}
这篇关于衡量用户在网站访问期间花费的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!