Skip to content

Instantly share code, notes, and snippets.

@roykolak
Created January 29, 2009 19:19
Show Gist options
  • Save roykolak/54685 to your computer and use it in GitHub Desktop.
Save roykolak/54685 to your computer and use it in GitHub Desktop.
Cookie Manager
CookieJar = {
cookies: {},
// Pass This: { name:'cookie', value:'value', [expires:'365'], [domain:'domain'], [path:'path'], [secure:true] }
addCookie:function(newCookie) {
cookie = [];
// Build the New Cookie Array
$.each(newCookie, function(index, value) {
switch(index) {
case 'name': cookie[0] = value;
break;
case 'value': cookie[0] = cookie[0] + "=" + $.trim(value);
break;
case 'expires': dateObj = new Date();
dateObj.setDate(dateObj.getDate() + parseInt(value));
value = dateObj.toGMTString();
cookie[1] = index + "=" + value;
break;
case 'path': cookie[2] = index + "=" + value;
break;
case 'domain': cookie[3] = index + "=" + value;
break;
case 'secure': if(value) { cookie[4] = index };
break;
}
});
// Remove Blanks in New Cookie Array
var cleanCookie = new Array();
for(i = 0; i < 5; i++) { if(cookie[i]) { cleanCookie.push(cookie[i]); } }
// Submit New Cookie
document.cookie = cleanCookie.join(';') + ';';
// Update Cookies Object and Return
return (CookieJar.packageCookies()) ? true : false
},
getCookie:function(cookie) {
return (CookieJar.cookies[cookie]) ? CookieJar.cookies[cookie] : false
},
updateCookie:function(cookie) {
return (CookieJar.getCookie(cookie.name)) ? CookieJar.addCookie(cookie) : false
},
tossCookie:function(cookie) {
// Ready the Cookie Object to Remove
oldCookie = {};
oldCookie.name = cookie;
oldCookie.value = CookieJar.getCookie(cookie);
oldCookie.expires = '0';
return CookieJar.updateCookie(oldCookie);
},
packageCookies:function() {
// Stores Available Cookies as Object
$.each(document.cookie.split(';'), function() {
name = $.trim(this.split('=')[0]);
value = this.split('=')[1];
CookieJar.cookies[name] = value;
});
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment