Cookie Manager

Class that can create/read/update/delete cookies in javascript

by infiniteloops

JavaScript

function CookieManager() {
    this.cookies = new Array();
};

CookieManager.prototype.setCookie = function(name, data) {
    var expires = "";
    var jsonData = JSON.stringify(data);
    document.cookie = name + "=" + jsonData + "; " + expires + "; path=/";
    if (this.cookies.indexOf(name) < 0) {
        this.cookies.push(name);
    }
};

CookieManager.prototype.readCookie = function(name) {
    if(name === undefined && this.cookies.length > 0){
        name = this.cookies[0];
    }
    if(jQuery.isNumeric(name)){        
        if(this.cookies.length - 1 >= name){
            name = this.cookies[name];
        }
    }
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ')
        c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return JSON.parse(c.substring(nameEQ.length, c.length));
    }
    return null;
};

CookieManager.prototype.emptyCookie = function(name) {
    this.setCookie(name, null);
    var ix = this.cookies.indexOf(name);
    this.cookies.splice(ix, 1);
};

// Wire up to jquery
jQuery.CookieManager = new CookieManager();

//EXAMPLE USAGE
//=============
// store array in cookie
var myData = ['id1', 'id2', 'id3'];
var myOtherData = { stuff: "data" };
$.CookieManager.setCookie('test', myData);
$.CookieManager.setCookie('test2', myOtherData);

// read data from cookie
console.log($.CookieManager.readCookie('test2'));
// read data from first cookie
console.log($.CookieManager.readCookie());
// read data from cookie based on insert index
console.log($.CookieManager.readCookie(1));

// list of known cookies kept
$.CookieManager.cookies.forEach(function(element){
    console.log(element);
});

// clear out data and remove from cookies list
$.CookieManager.emptyCookie('test');