Cookies in JavaScript
Reading and writing (getting and setting) cookies in JavaScript is a far uglier affair than it perhaps should be. Cookies fall between the cracks of different specifications and have never really been significantly readdressed beyond their original conception. As a result, we must write, or import code that parses cookie strings in order to read their values.
Below are examples of code that can read a named cookie, and write a new cookie that lasts for 1 day.
Reading Cookies
function getCookie(cookieName) {
var cookie = document.cookie.split( ';' );
for ( var i = 0; i < cookie.length; i++ ) {
var crumbs = cookie[i].split( ',' );
for ( var j = 0; j < crumbs.length; j++ ) {
var molecules = crumbs[j].split('=');
if (molecules[0].trim() == cookieName) {
return unescape(molecules[1]);
}
}
}
}
The getter code above is fairly straightforward, in that it breaks up the cookie string into its constituent parts and then loops over those parts in order to try and match the name that was given.
It is far from an optimal solution, but it is good enough. A better solution might be to avoid splitting the cookie strings up altogether and instead locate the desired cookie name within the string, and then read the subsequent characters until a comma is reached. This might also be a candidate for a function that uses memoization so that subsequent reads of the same cookie do not result in the full parsing process taking place.
Writing Cookies
function setCookie(name,value,daysToExpiry) {
var nowDate = new Date();
var millisecToExpiry = daysToExpiry * 24 * 60 * 60 * 1000;
var expireDate = new Date();
expireDate.setTime(nowDate.getTime()+millisecToExpiry);
var expiry = expireDate.toLocaleString();
var newCookie = name + "=" + escape(value) + ";expires=" + expiry;
document.cookie = newCookie;
}
The main client-side complication when writing cookies is that if an expiry date is required, it must be set using a string format of the date. To work out a date in the future, we must first find the current date, then add “some time” to that date, and then translate this new numerical date back into a string based one, before setting the cookie. The simplest way to do this is to get the current time in milliseconds since the unix epoch. The down side of this is that we have to work out what “some time” is in milliseconds. If we want to create a cookie that lasts 1 day we work out how many milliseconds there are in a day, add that amount to the current time, and set a cookie with that new time nicely formatted as a string. This is not a helpful API, but a simple setter function like the one above can be modified for most purposes.