Pages

Persistence by cookies

We can't access the secondary store on the local machine with JavaScript, with the exception of cookies. So, we use a cookie to store basic information for a page.

A cookie is identified by a unique name, it is used to store a value, and it has an expiration date. All the cookies are stored in a string associated to the current web page, that makes them a bit wierd to manage. So it is customary to write a tiny library of JavaScript functions to keep easy the user code.

Here is how we are going to save a cookie:

function writeCookie(name, value, secs) {
// by default the cookie is temporary
var expires = "";

// cookie persistent for the passed number of seconds
if(secs) {
var date = new Date();
date.setTime(date.getTime() + secs * 1000);
expires = "; expires=" + date.toGMTString();
}

// set the cookie to the name, value, and expiration date
document.cookie = name + "=" + value + expires + "; path=/";
}

Normally, it would be more useful if the third parameter of writeCookie() was the number of days. But for testing purposes it is handy having a cookie that expires in a few seconds.

Once a cookie is stored, we should retrieve it:

function readCookie(name) {
var searchName = name + "=";
var cookies = document.cookie.split(';');
for(var i=0; i < cookies.length; i++) {
var c = cookies[i];
while (c.charAt(0) == ' ')
c = c.substring(1, c.length);
if (c.indexOf(searchName) == 0)
return c.substring(searchName.length, c.length);
}
return null;
}

As we said, the code is a bit involute. We split document.cookie in an array of cookies, using semicolon (";") as delimiter. [This is cool, but it leads to the inconvenience that we can't store semicolon in our cookie!]
Then we loop on all the cookies, we skip all the trailing blanks, and check for the key, if we find it then we return the substring starting just after the equal sign to the end of the current cookie.

To erase a cookie we just change it assigning a negative value as expiration:

function eraseCookie(name) {
writeCookie(name, "", -1);
}


More on JavaScript cookies in chapter three of Head First JavaScript.

No comments:

Post a Comment