Easy cookie management

9th January 2014

Cookies are still the most reliable way of storing data across sessions in all browsers. But handling cookies in Javascript is a bit of a pain as you need to parse and encode cookie information manually. You can use the Javascript class below to do this for you:

var Cookies = {
deleteAllCookies: function() {
var cookies = Cookies.getCookies();

for (var name in cookies) {
if (cookies.hasOwnProperty(name)) {
Cookies.deleteCookie(name);
}
}
},
getCookie: function(name) {
var allCookies = Cookies.getCookies();

if (name in allCookies) {
return allCookies[name];
} else {
return null;
}
},
getCookies: function() {
var cookies = { };

if (document.cookie && document.cookie != "") {
var split = document.cookie.split(";");

for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, "");
cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
}
}

return cookies;
},
createCookie: function(name,value,hours) {
var expires = "";

if (hours) {
var date = new Date();
date.setTime(date.getTime()+(hours*3600000));
expires = "; expires=" + date.toGMTString();
}

document.cookie = name + "=" + value + expires + "; path=/";
},
deleteCookie: function(name) {
Cookies.createCookie(name, "" ,-1);
}
};

Usage

The example below shows what methods should be called to store cookies using the Javascript file above:

Cookies.createCookie("quality", "low"); //sets or overwrites an existing cookie
Cookies.getCookie("quality"); // returns the cookie value 'low'

A caution about using cookies

Cookie information is passed from the browser to the server for every request in the headers. Storing a lot of information in cookies can slow down the user experience. Sensitive information (should as their personal details, email or login details) should not be stored in cookies, at least not on a non-HTTPS website. Websites serving the United Kingdom should also notify the user what cookies they are storing about them in their policy files.

Make a comment

Contribute to this article and have your say.