TMH*_*ign 6 html javascript cookies session-storage
我想要一个脚本来计算一个人在我的网站的一次会话期间点击的页面数量,并可能还记录每个 URL。目的是在提交表单时,我想填充表单的两个隐藏字段,一个包含页面,另一个包含会话期间访问的 url 序列。
最初我想用cookie来做到这一点,在每个页面上,读取并获取cookie的当前值,将其存储在变量中,删除cookie,并使用附加的重写cookie多变的。我打算使用纯 JavaScript。
然后我遇到了 HTML5 sessionStorage 并认为这可能是一个很好的解决方案。
这是我当前的代码,可以计算访问的页面数。我担心的是,使用此方法记录 url 可能会超出 cookie 的大小分配。
有没有更好的办法?我应该考虑 HTML5 存储吗?
下面是我的工作代码。我对其进行了编码,以便在每个页面上查找具有 ID pageCount 的表单元素,如果存在,则用我的值填充它。
我还计划使用经典 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;
}
}
Run Code Online (Sandbox Code Playgroud)
我很想使用sessionStorage这个任务,因为它可以存储比 cookie 更多的数量,并且您不必担心在任何阶段手动将其删除,因为它只会保留在会话中。
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 );
Run Code Online (Sandbox Code Playgroud)
显示存储数据的表单示例
<!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>
Run Code Online (Sandbox Code Playgroud)