dongpou1935
dongpou1935
2016-12-23 19:30

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

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.

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongmeixian9665 dongmeixian9665 5年前

    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];
            }
        });
    }
    

    JSFiddle

    点赞 5 评论 复制链接分享
  • dongyijing2353 dongyijing2353 5年前

    Using localStorage may not be the best choice for what you need. But sessionStorage, and localStorage is most suitable. Have in mind that sessionStorage when opening a new tab resolves to a new session, so using localStorage has to do with the fact that if only sessionStorage was used and a user opened a new tab in parallel and visit your website would resolve to a new separate session for that browser tab and would count timeOnSite from start for it. In the following example it is tried for this to be avoid and count the exact timeOnSite.

    The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.

    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.");
    }
    

    Working fiddle

    If you want a server-side solution then set a $_SESSION['timeOnSite'] variable and update accordingly on each page navigation.

    点赞 评论 复制链接分享