How to use Javascript to Count Total Pages Visited in 1 Session
Asked Answered
O

2

6

I want to have a script that will count the number of pages that a person hits during one session to my website, and possibly record each URL as well. The purpose is such that upon submitting a form, I want to populate two hidden fields of the form, one with page, the other with the sequence of urls visited during the session.

Initially I thought of doing this with cookies, and on each page, read & get the current value of the cookie(s), store that in a variable, delete the cookie(s), and rewrite the cookie(s) with an appended variable. I was going to use plain javascript.

Then I came across HTML5 sessionStorage and think that might be a good solution.

This is my current code which works insofar as counting pages visited. My concern is that using this method to record urls might exceed the size allotment for cookies.

Is there a better way? Should I be looking at HTML5 Storage instead?

Here is my working code below. I coded it such that on each page, it looks for a form element with ID pageCount, and if present populates it with my value.

I also plan to use this - Request.Servervariables("HTTP_X_ORIGINAL_URL") - from classic ASP to build a list of pages visited and store those in a cookie or storage.

var page_count =  (document.cookie.match(/^(?:.*;)?\s*pageCount\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1];

function createCookie(name,value,days) {

    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";

}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name,"",-1);
}
var element =  document.getElementById('pageCount');
if(page_count == null){
createCookie('pageCount','1',1);
if (typeof(element) != 'undefined' && element != null){
document.getElementById("pageCount").value = "1";
}
}else{
var x = parseInt(readCookie('pageCount')) + 1;
eraseCookie('pageCount');
createCookie('pageCount',x,1);
if (typeof(element) != 'undefined' && element != null){
document.getElementById("pageCount").value = x;
}
}
Orange answered 21/11, 2019 at 11:57 Comment(1)
local/session Storage is limited to, I believe, 5Mb whereas a cookie is limited to 4096bytes...which suggests local/session storage to be the better optionYoakum
Y
3

I would be tempted to use sessionStorage for this task as it can store a greater amount than a cookie and you needn't worry about manually tearing it down at any stage because it will only remain for the session.

const hitcounter=function(){
    const StoreFactory=function( name, type ){/* this would usually be in a separate js file */
        'use strict';
        const engine = !type || type.toLowerCase() === 'local' ? localStorage : sessionStorage;

        const set=function( data ){
            engine.setItem( name, JSON.stringify( data ) );
        };
        const get=function(){
            return exists( name ) ? JSON.parse( engine.getItem( name ) ) : false;
        };
        const remove=function(){
            engine.removeItem( name );
        };
        const exists=function(){
            return engine.getItem( name )==null ? false : true;
        };
        const create=function(){
            if( !exists() ) set( arguments[0] || {} );
        };
        return Object.freeze({
            set,
            get,
            exists,
            create,
            remove
        });
    }

    let oStore = new StoreFactory( 'urls', 'sessionStorage' );
        oStore.create();

    let data=oStore.get();
        data[ location.href ]=data.hasOwnProperty( location.href ) ? parseInt( data[ location.href ] ) + 1 : 1;
        data.total=data.hasOwnProperty('total') ? parseInt( data.total ) + 1 : 1;

    oStore.set( data );
}
document.addEventListener( 'DOMContentLoaded', hitcounter );

An example with a form to display stored data

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>sessionStorage: Maintain list of visited URLS</title>
        <style>
            span{color:green;display:block;clear:both;}
            ul{color:blue}

        </style>
        <script>
            const hitcounter=function(){
                const StoreFactory=function( name, type ){/* this would usually be in a separate js file */
                    'use strict';
                    const engine = !type || type.toLowerCase() === 'local' ? localStorage : sessionStorage;
                    const set=function( data ){
                        engine.setItem( name, JSON.stringify( data ) );
                    };
                    const get=function(){
                        return exists( name ) ? JSON.parse( engine.getItem( name ) ) : false;
                    };
                    const remove=function(){
                        engine.removeItem( name );
                    };
                    const exists=function(){
                        return engine.getItem( name )==null ? false : true;
                    };
                    const create=function(){
                        if( !exists() ) set( arguments[0] || {} );
                    };
                    return Object.freeze({
                        set,
                        get,
                        exists,
                        create,
                        remove
                    });
                };

                const clickhandler=function(e){
                    oList.innerText = oSpan.innerText = '';

                    let json=oStore.get();

                    Object.keys( json ).map( key =>{
                        let li=document.createElement('li');
                            li.innerText=key+' '+json[ key ]
                        if( key!='total' ) oList.appendChild( li )
                    });

                    oSpan.innerText='The total is: '+json.total;
                };



                let oStore = new StoreFactory( 'urls', 'sessionStorage' );
                    oStore.create();
                let data=oStore.get();
                    data[ location.href ]=data.hasOwnProperty( location.href ) ? parseInt( data[ location.href ] ) + 1 : 1;
                    data.total=data.hasOwnProperty('total') ? parseInt( data.total ) + 1 : 1;
                oStore.set( data );


                let oList=document.querySelector( 'form > ul' );
                let oSpan=document.querySelector( 'form > span' );
                let oBttn=document.querySelector( 'form > input[ type="button"]' );
                    oBttn.addEventListener('click', clickhandler )
            }
            document.addEventListener( 'DOMContentLoaded', hitcounter );
        </script>
    </head>
    <body>
        <form method='post'>
            <ul></ul>
            <span></span>
            <input type='button' value='Load data' />
        </form>
    </body>
</html>
Yoakum answered 21/11, 2019 at 12:28 Comment(6)
RamRaider, I can not thank you enough for this. To be honest it is way above my head - but it seems to work great! I put it on my website and I can see it recording each url as I navigate the website. Question please. It increments with a page refresh, can refreshes be excluded somehow? Also, I am including this on every page in a website. If a user visits a page with a form that has an input(s) with given ID(s), extract the total page count and place urls in a form field such that each would be on their own line (or delimited someway using a character such as ~)Orange
To avoid counting page refreshes you could make the above way more complicated to include timestamps and then not allow if the last timestamp was X seconds ago etc. Probably too complicated. Alternatively record each URL a single time only. As for displaying the urls stored in a form that is very easy: use the oStore.get() to fetch the stored data and iterate through itYoakum
Thank you. I would really appreciate a bit more help with this as I am but a beginner with javascript. I put this on a page in my website: document.getElementById("result").innerHTML = sessionStorage.getItem("urls"); and sure enough it populates my element with the contents of urls - {"mywebsite.com/appointment/….....} That is a JSON array (object?) correct? Now I would need to somehow write a script to get the total count in this case 6, into one element, and seperate the urls and place them in another element?Orange
Correct - the data you see is a JSON string. Also correct you need to process that string and recover whatever details you need from it.Yoakum
RamRaider, I can not even begin to thank you enough for this awesome script. I manage auto repair shop websites and I am using your script such when someone requests an estimate or appointment, my clients know not only how many pages that person looked at, but thanks to you what pages (and how many times each page) they looked at! You ROCK. Question: would it be hard to modify the script such that not only do I keep total / individual page count, but total aggregate time spent and time spent on each page? That would be a killer thing to include.Orange
you would need to fundamentally alter the data structure in order to record the times. Simple question though: as this is for statistical analysis of your visitors browsing behaviour why not use Google Analytics?Yoakum
T
2

okay this following example demonstrating how to calculate the count of the page visited using javascript

link to the jsfiddle

https://jsfiddle.net/msdnq04c/5/

have a look and let me know is it solving the purpose?

<button onclick="visited();">visited per session</button>

<script>
window.onload = function() {
localStorage.setItem('count', parseInt(localStorage.getItem('count'), 10)+1);
};

function visited(){
alert(localStorage.getItem('count'));
}

</script>

This is using Localstorage.

if we want to make count per session, we can use cookies and per cookies, we can store the count

Though answered 21/11, 2019 at 12:19 Comment(1)
code snippet might not work in SO, so follow js fiddle linkThough

© 2022 - 2024 — McMap. All rights reserved.