Search code examples
javascriptphpjqueryajaxtimer

Measure time spent by a user during a website visit


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.


Solution

  • Here's a working example. 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