JavaScript By Example

Updating Cookies

Woman working at laptop
Tetra Images/Getty Images

Actually updating a cookie is slightly different from just replacing a cookie in that the new value we want to place in the cookie is dependent in some way on whether the cookie already exists and if so on what it contains. This means that we need to read the existing cookie before we can write a replacement for it.

One thing to note is that when we read a cookie we have no way of telling when the existing cookie is due to expire or whether the cookie is restricted to a specific folder or available across the entire domain.

You need to set a new retention period when you replace the cookie and need to keep track of what scope you want the cookie to have within your pages so as to apply the same domain or path option each time. The only thing that you are actually able to read when updating rather than just replacing a cookie is the actual value of the data stored in the cookie.

In this example we are going to use a cookie named 'accesscount' to count the number of times that our visitor has accessed our page where no more than seven days has elapsed between visits. Should more than seven days elapse between visits then the cookie will expire and the next visit will restart counting from zero. We are using the allCookies() and writeCookie() functions from the prior examples so the only piece of new code we need in order to actually do the update is in the last two lines.


var cookie;
allCookies = function() {
var cr, ck, cv;
cr = []; if (document.cookie != '') {
ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
return cr;
};
writeCookie = function(cname, cvalue, days,opt) {
var dt, expires, option;
if (days) {
dt = new Date();
dt.setTime(dt.getTime()+(days*24*60*60*1000));
expires = "; expires="+dt.toGMTString();
} else expires = '';
if (opt) {
if ('/' = substr(opt,0,1)) option = "; path="+opt;
else option = "; domain="+opt;
} else option = '';
document.cookie = cname+"="+cvalue+expires+option;
}
 
cookie = allCookies();
 
if (cookie.accesscount != null) writeCookie('mycookie', cookie.accesscount + 1,7);
else writeCookie('mycookie', 1,7);