JavaScript for Setting Session ID and Visitor ID Cookies


Hi,
This blog guides you about how to store and retrieve cookies from Javascript. 

This code should be stored in a file named <filename>.js, e.g. cookie.js :

function Get_Cookie(name) {
   var start = document.cookie.indexOf(name+”=”);
   var len = start+name.length+1;
   if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
   if (start == -1) return null;
   var end = document.cookie.indexOf(“;”,len);
   if (end == -1) end = document.cookie.length;
   return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    var cookieString = name + “=” +escape(value) +
       ( (expires) ? “;expires=” + expires.toGMTString() : “”) +
       ( (path) ? “;path=” + path : “”) +
       ( (domain) ? “;domain=” + domain : “”) +
       ( (secure) ? “;secure” : “”);
    document.cookie = cookieString;
}

function Delete_Cookie(name,path,domain) {
   if (Get_Cookie(name)) document.cookie = name + “=” +
      ( (path) ? “;path=” + path : “”) +
      ( (domain) ? “;domain=” + domain : “”) +
      “;expires=Thu, 01-Jan-70 00:00:01 GMT”;
}

var today = new Date();
var zero_date = new Date(0,0,0);
today.setTime(today.getTime() – zero_date.getTime());
var cookie_expire_date = new Date(today.getTime() + (8 * 7 * 86400000));

function setVisitorID() {
   if (Get_Cookie(‘VisitorID’)) {
       var VisitorID = Get_Cookie(‘VisitorID’);
   }else{
       Set_Cookie(‘VisitorID’,Math.random(),cookie_expire_date);
   }
}

function setSessionID() {
   if (!Get_Cookie(‘SessionID’))
       Set_Cookie(‘SessionID’,Math.random());
}

var loaded_script = true;

This is an example of how to set a cookie in your HTML pages:

<html>
<head>
<title>Test Page</title>
<script src=”test.js” mce_src=”test.js”></script>
<script language=”javascript”>
//This line could be used to set a cookie manually
//Set_Cookie( “key” , “val” , cookie_expire_date , “/stuff” , false );

//This line is used to set a visitor ID, which is easier
setVisitorID();
</script>
</head>
<body>
<br>This is only a test.<br>
</body>
</html>

Now, in your Analyzer configuration, you can set the Cookie Name to “VisitorID” (without the quotes), to provide better tracking for your site. However, be sure that your web server log files do log and contain cookie information.

I found this useful code snippent from http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm

Advertisements