简体   繁体   中英

How to use Javascript to Count Total Pages Visited in 1 Session

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM