Skip to content

Instantly share code, notes, and snippets.

@CodeAngry
Last active Aug 29, 2015
Embed
What would you like to do?
Cookie Monster is a simple JS cookie manager.
/**
* CookieMonster.JS
*
* @copyright Claude Adrian, CodeAngry
* @license http://www.wtfpl.net/
*/
;(function(){
if (typeof String.prototype.trimLeft !== 'function') {
String.prototype.trimLeft = function() {
return this.replace(/^\s+/, '');
};
}
if (typeof String.prototype.trimRight !== 'function') {
String.prototype.trimRight = function() {
return this.replace(/\s+$/, '');
};
}
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.trimLeft().trimRight();
};
}
})();
/**
* Exposed methods:
*
* document.cookies.refresh();
* document.cookies.count();
* document.cookies.clear();
* document.cookies.name(name_or_index);
* document.cookies.value(name_or_index);
* document.cookies.find(name_or_index);
* document.cookies.is(name_or_index);
* document.cookies.get(name_or_index);
* document.cookies.set(name, value, expires, path, domain, secure);
* document.cookies.unset(name, path, domain, secure, refresh);
*/
;(function(window, document, undefined){
// Make object publicly accessible.
document.cookies = window.cookies = ({
/* ------------------------- PROPERTIES ------------------------- */
// Store current url information
url: {},
// Store names of cookies
names: [],
// Store values of cookies
values: [],
// Store values of cookies
pairs: {},
/* ------------------------- METHODS ------------------------- */
// Cookie count
count: function(){
return this.pairs.length;
},
// Name of cookie by index
name: function(name_or_index){
if(typeof name_or_index === 'string'){
name_or_index = name_or_index.trim();
if(RegExp('^[0-9]+$').test(name_or_index)){
name_or_index = parseInt(name_or_index);
}else{
if(!name_or_index.length){
return -1;
}
return this.name(this.find(name_or_index));
}
}
if(typeof name_or_index === 'number'){
name_or_index = parseInt(name_or_index);
if(name_or_index < 0 || name_or_index >= this.count()){
return null;
}
return this.names[name_or_index];
}
return null;
},
// Value of cookie by index
value: function(name_or_index){
if(typeof name_or_index === 'string'){
name_or_index = name_or_index.trim();
if(RegExp('^[0-9]+$').test(name_or_index)){
name_or_index = parseInt(name_or_index);
}else{
if(!name_or_index.length){
return -1;
}
return value(find(this.find(name_or_index)));
}
}
if(typeof name_or_index === 'number'){
name_or_index = parseInt(name_or_index);
if(name_or_index < 0 || name_or_index >= this.count()){
return null;
}
return this.values[name_or_index];
}
return null;
},
// Find index of a cookie
find: function(name_or_index){
if(typeof name_or_index === 'string'){
name_or_index = name_or_index.trim();
if(RegExp('^[0-9]+$').test(name_or_index)){
name_or_index = parseInt(name_or_index);
}else{
if(!name_or_index.length){
return -1;
}
for(var pos = 0; pos < this.names.length; pos++){
var cookieName = this.names[pos];
if(cookieName.toLowerCase() == name_or_index.toLowerCase()){
return pos;
}
}
return -1;
}
}
if(typeof name_or_index === 'number'){
name_or_index = parseInt(name_or_index);
if(name_or_index < 0 || name_or_index >= this.count()){
return -1;
}
return name_or_index;
}
return -1;
},
// Cookie exists?
is: function(name_or_index){
return find(name_or_index) != -1;
},
// Drop all cookies, won't work for HTTP only
clear: function(){
for(var key in this.names){
this.unset(this.names[key]);
}
return this.refresh();
},
// Drop a cookie
unset: function(name, path, domain, secure, refresh){
if(typeof name !== 'string'){
return false;
}
name = name.trim();
if(!name.length){
return false;
}
if(typeof path === 'undefined'){
path = '/';
}
if(typeof domain === 'undefined'){
domain = document.location.hostname;
}
if(typeof refresh === 'undefined'){
refresh = true;
}
if(typeof secure === 'undefined'){
secure = (document.location.protocol === 'https:');
}
if(typeof path !== 'string' || !path.length){
path = '/';
}
document.cookie = name + "=" +
((path) ? ";path=" + path : '') +
((domain) ? ";domain=" + domain : '') +
";max-age=-1; expires=Thu, 01-Jan-1970 00:00:01 GMT" +
((secure) ? ";secure" : '');
if(refresh){
this.refresh();
}
return true;
},
// Get cookie value
get: function(name_or_index){
var index = this.find(name_or_index);
return (index == -1) ? null : this.values[index];
},
// Set a cookie, update old or create new
set: function(name, value, expires, path, domain, secure){
if(typeof name !== 'string'){
return false;
}
name = name.trim();
if(!name.length){
return false;
}
if(typeof path === 'undefined'){
path = '/';
}
if(typeof domain === 'undefined'){
domain = document.location.hostname;
}
if(typeof secure === 'undefined'){
secure = (document.location.protocol === 'https:');
}
if (value === null) {
return this.unset(name, path, domain);
}
if(typeof value === 'undefined'){
return false;
}
if(path === null){
path = document.location.pathname;
}
if(domain === null){
domain = document.location.hostname;
}
if(typeof path !== 'string'){
return false;
}
if(typeof domain !== 'string'){
return false;
}
if(!path.length){
path = document.location.pathname;
}else if(path === '?'){
path = document.location.pathname + document.location.search;
}
if(!domain.length){
domain = document.location.hostname;
}
var components = [];
components.push(name + '=' + encodeURIComponent(value));
if(expires){
var seconds = 0;
var date = null;
if(expires instanceof Date){
seconds = parseInt((Date().getTime() - expires.getTime()) / 1000);
}else if(typeof expires === 'number'){
seconds = expires;
}else if(typeof expires === 'string'){
if(RegExp('^[0-9]+$').test(expires)){
seconds = parseInt(expires);
}else{
var matches = RegExp('^([\\+\\-])\\s*([0-9]*\\.[0-9]*)\\s*' +
'(second|minute|hour|day|week|month|year)s?$', 'i').exec(expires);
if(matches){
date = new Date();
var sign = matches[1], offset = parseFloat(matches[2]), unit = matches[3];
if(sign === '-'){
offset = - offset;
}
if(unit === 'second'){
seconds = offset;
}else if(unit === 'minute'){
seconds = offset * 60;
}else if(unit === 'hour'){
seconds = offset * 60 * 60;
}else if(unit === 'day'){
seconds = offset * 24 * 60 * 60;
}else if(unit === 'week'){
seconds = offset * 7 * 24 * 60 * 60;
}
}
}
}else{
return false;
}
if(seconds = parseInt(seconds)){
components.push('max-age=' + seconds);
var date = new Date();
date.setTime(date.getTime() + (seconds * 1000));
components.push('expires=' + date.toUTCString());
}
}
if((typeof path === 'string') && path.length){
components.push('path=' + path);
}
if((typeof domain === 'string') && domain.length){
components.push('domain=' + domain);
}
if(secure){
components.push('secure');
}
document.cookie = components.join(';');
this.refresh();
return true;
},
// Refresh internal cookie arrays
refresh: function(){
this.url.query = document.location.search;
this.url.path = document.location.pathname;
this.url.pathqs = this.url.path + this.url.query;
this.url.url = document.location.href;
this.url.urlqs = this.url.url + this.url.query;
this.url.host = document.location.hostname;
this.url.port = document.location.port;
this.url.hostport = document.location.host;
this.url.proto = document.location.protocol;
this.url.hash = this.url.target = document.location.hash;
this.names = [];
this.values = [];
this.pairs = {};
var documentCookies = document.cookie.split(';');
for(var pos = 0; pos < documentCookies.length; pos++){
var documentCookie = documentCookies[pos].trim();
var cookieParts = documentCookie.split('=', 2);
if(cookieParts.length != 2){
continue;
}
var cookieName = decodeURIComponent(cookieParts[0].trim());
var cookieValue = decodeURIComponent(cookieParts[1].trim());
this.names.push(cookieName);
this.values.push(cookieValue);
this.pairs[cookieName] = cookieValue;
}
return this;
}
}).refresh();
})(window, document, undefined);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment