Hemanth's Scribes

javascript

Simple Cookie Management with JavaScript

Author Photo

Hemanth HM

Thumbnail

One of the most common things that most web developers would do is cookie management.

Was pawing at some JavaScript and made a simple cookie management class in JavaScript that does basic cookie management like:

  • setCookie
  • getCookie
  • removeCookie
  • getAll
  • removeAll

Okies, so now enough of talking, here is the silly code:

/*
 * @author      Hemanth.HM 
 * @version     0.1
 * @desc        JavaScript cookie management.
 * @license     GNU GPLv3 
 */

manageCookie = {
    /**
     * Set a cookie's value
     * @param  name  string  Cookie's name.
     * @param  value string  Cookie's value.
     * @param  days  int     Number of days for expiry.
     */
    setCookie: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        } else {
            var expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    /**
     * Get a cookie's value
     * @param  name  string  Cookie's name.
     * @return value of the Cookie.
     */
    getCookie: function(name) {
        var coname = name + "=";
        var co = document.cookie.split(';');
        for (var i = 0; i < co.length; i++) {
            var c = co[i];
            c = c.replace(/^\s+/, '');
            if (c.indexOf(coname) == 0) {
                return c.substring(coname.length, c.length);
            }
        }
        return null;
    },

    /**
     * Removes a cookie
     * @param  name  string  Cookie's name.
     */
    removeCookie: function(name) {
        manageCookie.setCookie(name, "", -1);
    },

    /**
     * Returns an object with all the cookies.
     */
    getAll: function() {
        var splits = document.cookie.split(";");
        var cookies = {};
        for (var i = 0; i < splits.length; i++) {
            var split = splits[i].split("=");
            cookies[split[0]] = unescape(split[1]);
        }
        return cookies;
    },

    /**
     * Removes all the cookies
     */
    removeAll: function() {
        var cookies = manageCookie.getAll();
        for (var key in cookies) {
            if (cookies.hasOwnProperty(key)) {
                manageCookie.removeCookie(key);
            }
        }
    }
};
#javascript
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.