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:

 timeSite = new Date()-time;

I've search everywhere for the solution but with no luck, if anyone knows how to do this please let me know.

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


  • 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 =;
        timer = setInterval(function(){
            timeSpentOnSite = getTimeSpentOnSite()+(;
            timerStart = parseInt(;
            // Convert to seconds

    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
                    // Window is active
                documentIsHidden = document[hidden];


    点赞 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 =;
       if(!localStorage.getItem('timeOnSite')) {
       } else {
       if(localStorage.getItem('tabsCount') && parseInt(localStorage.getItem('tabsCount'))>1){
       } else {
    var myInterval = setInterval(function(){  
       var time ='firstVisitTime'));
       document.getElementById("output").innerHTML = (time/1000)+' seconds have passed since first visit';
    }, 1000);
    return myInterval;
    window.onbeforeunload=function() {
    console.log('Document onbeforeunload state.');
    window.onunload=function() {
    var time =;
    console.log('Document onunload state.');
    if (document.readyState == "complete") {
    var timer = myTimer();
    } else {
       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.

    点赞 评论 复制链接分享