简体   繁体   English

如何使用 Javascript 计算 1 Session 中访问的总页数

[英]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.我想要一个脚本来计算一个人在一个 session 到我的网站期间点击的页面数,并且可能还记录每个 URL。 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.目的是在提交表单时,我想填充表单的两个隐藏字段,一个带有页面,另一个带有在 session 期间访问的 url 序列。

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.最初我想用 cookies 来做这件事,在每个页面上,读取并获取 cookie 的当前值,将其存储在变量中,删除 cookie,并用附加的重写 cookie多变的。 I was going to use plain javascript.我打算使用普通的 javascript。

Then I came across HTML5 sessionStorage and think that might be a good solution.然后我遇到了 HTML5 sessionStorage 并认为这可能是一个很好的解决方案。

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.我担心使用这种方法记录 url 可能会超出 cookies 的大小分配。

Is there a better way?有没有更好的办法? Should I be looking at HTML5 Storage instead?我应该改用 HTML5 存储吗?

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.我对它进行了编码,以便在每个页面上,它都会查找 ID 为 pageCount 的表单元素,如果存在,则使用我的值填充它。

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.我还计划使用来自经典 ASP 的 Request.Servervariables("HTTP_X_ORIGINAL_URL") 来构建访问过的页面列表并将其存储在 cookie 或存储中。

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.我很想将sessionStorage用于此任务,因为它可以存储比 cookie 更多的数量,并且您不必担心在任何阶段手动将其拆除,因为它只会保留在 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好的,下面的示例演示了如何使用 javascript 计算访问页面的计数

link to the jsfiddle链接到 jsfiddle

https://jsfiddle.net/msdnq04c/5/ 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如果我们想按 session 计数,我们可以使用 cookies 和按 cookies,我们可以存储计数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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