Languages
[Edit]
EN

JavaScript - get / set / remove cookies with own manager

7 points
Created by:
Aisha
298

In this short article we would like to show how to get, set and remove cookies in JavaScript in web browser with own light cookies manager implementation.

By default cookies usage with built-in web browser API is not intuitive. It is reasone why a lot of libraries appeard. In practice we are able to wite own one cookies manager what what show in this article.

The example presented in the article was created to store cookies in safe way - escaping dangerous characters with encodeURIComponent() function, that can be changed to some other if it is needed.

The manager provides API to:

  • check if cookies are enabled
  • get text, boolean, number and date value cookies
  • set text, boolean, number and date value cookies,
  • remove cookie,
  • calculate expiration time from: seconds, minutes, hours and days.
Set and get cookies with JavaScript in web browser.
Set and get cookies with JavaScript in web browser.

Usage example:

var expiration = Cookies.calculateExpirationDays(30); // cookies will expire after 30 days

Cookies.setTextCookie('user', 'john', expiration);
Cookies.setBooleanCookie('admin', true , expiration);
Cookies.setNumberCookie('age', 25, expiration);
Cookies.setDateCookie('created', new Date(), expiration);

var user = Cookies.getTextCookie('user');
var admin = Cookies.getBooleanCookie('admin');
var age = Cookies.getNumberCookie('age');
var created = Cookies.getDateCookie('created');

Full API:

Cookies.checkCookiesEnabled()

Cookies.removeCookieValue(name)

Cookies.getTextCookie(name)

Cookies.setTextCookie(name, value, expiration, domain, path)

Cookies.getBooleanCookie(name)

Cookies.setBooleanCookie(name, value, expiration, domain, path)

Cookies.getNumberCookie(name)

Cookies.setNumberCookie(name, value, expiration, domain, path)

Cookies.getDateCookie(name)

Cookies.setDateCookie(name, value, expiration, domain, path)

Cookies.calculateExpirationSeconds(seconds)

Cookies.calculateExpirationMinutes(minutes)

Cookies.calculateExpirationHours(hours)

Cookies.calculateExpirationDays(days)

Where:

  • expiration, domain and path are optional,
  • calculatExpiration... functions return time when cookie will expire.

Practical example: 

// ONLINE-RUNNER:browser;

window.Cookies = new function() {
    var self = this;

    var cachedCookies = { };
    var browserCookie = document.cookie;

    if (browserCookie.length > 0) {
        var parts = browserCookie.split('; ');
        for (var i = 0; i < parts.length; ++i) {
            var entry = parts[i];
            var index = entry.indexOf('=');
            var name = decodeURIComponent(entry.substr(0, index));
          	if (name in cachedCookies) {
            	continue;
            }
            var value = decodeURIComponent(entry.substr(index + 1));
            setCachedCookie(name, value);
        }
    }

    function setCachedCookie(name, value) {
        cachedCookies[name] = value;
    }
    function removeCachedCookie(name) {
        delete cachedCookies[name];
    }
    function setBrowserCookie(name, value, expiration, domain, path) {
        var cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);
        if (expiration) {
          	cookie += ";expires=" + expiration.toUTCString();
        }
        if (domain) {
        	cookie += ';domain=' + encodeURIComponent(domain); //TODO: verify
        }
        if (path) {
        	cookie += ";path=" + encodeURIComponent(path); //TODO: verify
        }
        document.cookie = cookie;
    }
    function removeBrowserCookie(name) {
        var expiration = this.calculateDays(-100);
        document.cookie = encodeURIComponent(name) + ";expires=" + expiration.toUTCString();
    }

  	// Cookies API
  
    self.checkCookiesEnabled = function() {
        return navigator.cookieEnabled;
    };

    self.removeCookieValue = function(name) {
        removeCachedCookie(name);
        removeBrowserCookie(name);
    };

    self.getTextCookie = function(name) {
        return cachedCookies[name] || null;
    };
    self.setTextCookie = function(name, value, expiration, domain, path) {
        setCachedCookie(name, value);
        setBrowserCookie(name, value, expiration, domain, path);
    };

    self.getBooleanCookie = function(name) {
        var cookie = self.getTextCookie(name);
        if (cookie == null) {
          	return null;
        }
        return cookie == 'true' || cookie == '1';
    };
    self.setBooleanCookie = function(name, value, expiration, domain, path) {
        var text = value.toString();
        self.setTextCookie(name, text, expiration, domain, path);
    };

    self.getNumberCookie = function(name) {
        var cookie = this.getTextCookie(name);
        if (cookie == null) {
        	return null;
        }
        return parseFloat(cookie);
    };
    self.setNumberCookie = function(name, value, expiration, domain, path) {
        var text = value.toString();
        self.setTextCookie(name, text, expiration, domain, path);
    };

    self.getDateCookie = function(name) {
        var cookie = self.getNumberCookie(name);
        if (cookie == null) {
            return null;
        }
        return new Date(cookie);
    };
    self.setDateCookie = function(name, value, expiration, domain, path) {
        var text = value.getTime();
        self.setNumberCookie(name, text, expiration, domain, path);
    };

    // Cookies Utils

    self.calculateExpirationSeconds = function(value) {
        var now = Date.now();
        return new Date(now + 1000 * value);
    };
    self.calculateExpirationMinutes = function(value) {
        var now = Date.now();
        return new Date(now + 60000 * value); // 60 * 1000 = 60000
    };
    self.calculateExpirationHours = function(value) {
        var now = Date.now();
        return new Date(now + 3600000 * value); // 60 * 60 * 1000 = 3600000
    };
    self.calculateExpirationDays = function(value) {
        var now = Date.now();
        return new Date(now + 86400000 * value); // 24 * 60 * 60 * 1000 = 86400000
    };
};

// Usage example:

console.log('Cookies are ' + (Cookies.checkCookiesEnabled() ? 'enabled' : 'disabled'));

if (Cookies.checkCookiesEnabled()) {
    var expiration = Cookies.calculateExpirationSeconds(5);       // cookies stored only 5s
  	//               Cookies.calculateExpirationMinutes(minutes); // in minutes
	//               Cookies.calculateExpirationHours(hours);     // in hours
	//               Cookies.calculateExpirationDays(days);       // in days

  	Cookies.setTextCookie('user', 'john', expiration);
    Cookies.setBooleanCookie('admin', true , expiration);
    Cookies.setNumberCookie('age', 25, expiration);
    Cookies.setDateCookie('created', new Date(), expiration);

  	var user = Cookies.getTextCookie('user');
	var admin = Cookies.getBooleanCookie('admin');
	var age = Cookies.getNumberCookie('age');
	var created = Cookies.getDateCookie('created');
  
  	if (created) {
    	created = created.toISOString();
    }
  
  	console.log('user: '    + user    + '\n' +
                'admin: '   + admin   + '\n' +
                'age: '     + age     + '\n' +
                'created: ' + created        );
};

 

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join