davesmiths
2/25/2014 - 11:53 AM

cookies, javascript

cookies, javascript

var cookie = (function() {

    'use strict';
    
    var cookie = {};
    
    cookie.write = function(name, value, days, domain, path) {
        var date, expires = '', output;
        if (days) {
            date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = '; expires=' + date.toUTCString();
        }
        path = '; path=' + (path || '/');
        domain = domain === undefined ? 1 : domain;
        if (!isNaN(parseFloat(domain)) && isFinite(domain)) {
            domain = '.' + window.location.href.split('//')[1].split('/')[0].split(':')[0].split('.').slice(-(domain + 1)).join('.');
            // A note on cookie ports, which are removed from the domain equation http://stackoverflow.com/questions/1612177/are-http-cookies-port-specific
        }
        if (domain !== '') {
            domain = '; Domain=' + domain;
        }
        // isNumber thanks to http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
        document.cookie = output = name + '=' + value + expires + path + domain;
        return output;
    };
    
    cookie.read = function(name) {
        var nameEQ = name + '='
            ,ca = document.cookie.split(';')
            ,c
            ,i
        ;
        for (i = 0; i < ca.length; i++) {
            c = ca[i];
            while (c.charAt(0) === ' ') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) === 0) {
                return c.substring(nameEQ.length,c.length);
            }
        }
        return null;
    };
    
    cookie.erase = function(name, domain) {
        return cookie.write(name, '', -1, domain);
    };
    
    return cookie;
    
}());


// Usage
// cookie.write(name, value[, days][, domain][, path])
// cookie.read(name)
// cookie.erase(name[, domain])

// Say we're on the domain sub.bonza.com

// cookie.write('Name', 'Value', 3)
// -> Cookie created called "Name" with the value "Value", it will expire in 3 days, path is "/" and the domain is ".bonza.com"

// cookie.write('Name', 'Value', 3, 2)
// -> Difference here is the domain is now ".sub.bonza.com"

// cookie.erase('Name')
// -> Cookie called "Name" associated with the domain ".bonza.com" is deleted (set to expire yesterday) 

// cookie.erase('Name', 2)
// -> Cookie called "Name" associated with the domain ".sub.bonza.com" is deleted