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