Notice:

This page has been converted from a dynamic Wordpress article to a static HTML document. As a result, some content may missing or not rendered correctly.

JavaScript Cookie Manager Object ~ Fri, 10 Dec 2010 16:40:48 +0000

There are plenty of articles out there that detail how to work with browser cookies in JavaScript. This is not one of those. This article is about an object I have written to make working with cookies easier.

Working on a problem with some third party software I came across the following code:

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
        begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
        end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}
function deleteCookie() {
    delCookie("cookie1");
    delCookie("cookie2");
    delCookie("cookie3");
}
function delCookie(name)
{
    if (getCookie(name)) {
        document.cookie = name + "=" +
        "; path=/" +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

I decided that was horribly inefficient, so I replaced it with:

function deleteCookie() {
    delCookie("cookie1");
    delCookie("cookie2");
    delCookie("cookie3");
}
function delCookie(name)
{
    if (typeof getCookie(name) !== "undefined") {
        document.cookie = name + "=0" +
            "; path=/" +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

var cookies = ({
    init: function() {
        var cs = document.cookie.split(';');
        var k, v, x;
        for (var i = 0, j = cs.length; i < j; i++) {
            x = cs[i].indexOf('=');
            k = cs[i].substring(0, x).replace(/^\s+/, '');
            v = unescape(cs[i].substring(x + 1, cs[i].length));

            this[k] = v;
        }

        delete this.init;

        return this;
    }
}).init();

function getCookie(name) {
    return cookies[name];
}

What is the difference? In the original code all of the cookies set for the document were parsed every time the getCookie function was called. Since this is inefficient code, all of the cookies are parsed for every call to delCookie. That happens at least three times in the (incorrectly named) deleteCookie function.

So, what I did is create a cookies object that parses the document cookies when the script is first run. As the object parses the cookies, it adds new properties to itself that represent the document cookies. I also re-write the getCookie function to merely return the desired property on the cookies object. If the cookie exists then a string will be returned, otherwise the undefined type will be returned.

After writing this handy little bit of code I decided that I would like to expand upon it for my own uses. The result of which is the following object:

var cookieManager = ({
    cookies: {},

    deleteCookie: function(name) {
        if (typeof this.cookies[name] !== "undefined") {
            document.cookie = name + "=0; expires=Thu, 01-Jan-70 00:00:01 GMT";
            delete this.cookies[name];
        }
    },

    getCookie: function(name) {
        return this.cookies[name];
    },

    setCookie: function(params) {
        var p = {
            name: "",
            value: "",
            expires: "",
            path: "",
            domain: "",
            secure: false
        }, c;

        if (typeof params !== "object" || typeof params.name !== "string" || typeof params.value !== "string") {
            return "Must specify an object with at least the name and value properties.";
        }

        for (var k in params) {
            if (params.hasOwnProperty(k)) {
                if (params[k] instanceof Date && k == "expires") {
                    p[k] = params[k].toGMTString();
                } else if (k == "expires" && !isNaN(+params[k])) {
                    p[k] = (new Date(params[k])).toGMTString();
                } else {
                    p[k] = params[k];
                }
            }
        }

        this.cookies[p.name] = p.value;
        c = p.name + "=" + escape(p.value);

        if (p.expires !== "") {
            c += "; expires=" + p.expires;
        }

        if (p.path !== "") {
            c += "; path=" + escape(p.path);
        }

        if (p.domain !== "") {
            c += "; domain=" + escape(p.domain);
        }

        c += (p.secure) ? "; secure" : "";
        document.cookie = c;
    },

    init: function() {
        var documentCookies = document.cookie.split(';'),
            cookieName, cookieValue, pos;

        for (var i = 0, j = documentCookies.length; i < j; i++) {
            pos = documentCookies[i].indexOf('=');
            cookieName = documentCookies[i].substring(0, pos).replace(/^\s+/, '');
            cookieValue = documentCookies[i].substring(pos + 1, documentCookies[i].length);

            this.cookies[cookieName] = unescape(cookieValue);
        }

        delete this.init;

        return this;
    }
}).init();

This cookieManager object provides all of the tools necessary to work with cookies in a JavaScript script. When the object is created it loads up all of the available cookies into cookieManager.cookies. You can add cookies with cookieManager.setCookie() and delete them with cookieManager.deleteCookie(). And you have two ways to access cookies: cookieManager.cookies.cookie_name and cookieManager.cookies.getCookie("cookie_name").

You can mess around with it using the JSFiddle.

Code,  JavaScript,  Technology

Comments

JavaScript Patterns, A Book Review &laquo; Room Full of Mirrors said (2010-12-23 16:42:23 GMT):

[...] « JavaScript Cookie Manager Object [...]