Getting and setting cookies without jQuery. The quickest approach

For every project, where I can’t use jQuery and must rely on pure Javascript, I must search the Internet over and over again to find some cookie setting and reading code. Finally, I decided to write a short memo to future myself, to have this code handy in my blog. Here it is.

A code for reading given cookie value:

function getCookie(a)
{
    var b = a + "=",
        c = document.cookie.split(";"),
        d = "",
        e = "",
        f = {};

    for (var g = 0; g < c.length; g++)
    {
        var h = c[g];

        while (h.charAt(0) == " ") h = h.substring(1, h.length);

        if (h.indexOf(b) === 0)
        {
            d = h.substring(b.length, h.length), e = d.substring(0, 1);

            if (e == "{")
            {
                f = JSON.parse(d);
                if ("v" in f) return f.v
            }

            return d == "undefined" ? undefined : decodeURIComponent(d)
        }
    }
    return null
};

And (a much shorter) setting counterpart:

function setCookie(a, b)
{
    document.cookie = a + "=" + encodeURIComponent(b);
};

That’s all, folks!

Leave a Reply