Skip to content

Instantly share code, notes, and snippets.

@creeperyang
Created January 22, 2015 04:31
Show Gist options
  • Save creeperyang/6a787c7a4168d7ac57fb to your computer and use it in GitHub Desktop.
Save creeperyang/6a787c7a4168d7ac57fb to your computer and use it in GitHub Desktop.
Manipulate cookies via js
function CreateCookieMan() {
var cookieStore = getCookies();
var getAll = function() {
return cookieStore;
};
var getItem = function(name) {
return cookieStore[name];
};
var setItem = function(name, value, end, path, domain, secure) {
if (!name || /^(?:expires|max\-age|path|domain|secure)$/i.test(name)) { return false; }
var prop,
cookie = '',
expires = '';
cookieStore[name] = value;
if (end) {
switch (end.constructor) {
case Number:
expires = end === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + end;
break;
case String:
expires = "; expires=" + end;
break;
case Date:
expires = "; expires=" + end.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires +
(domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "") + (secure ? "; secure" : "");
};
var removeItem = function(name, path, domain) {
if(!name) return false;
if(name in cookieStore) {
delete cookieStore[name];
document.cookie = encodeURIComponent(name) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' +
(domain ? "; domain=" + domain : "") + (path ? "; path=" + path : "");
return true;
} else {
return false;
}
};
return {
getAll: getAll,
getItem: getItem,
setItem: setItem,
removeItem: removeItem
}
function getCookies() {
var cookie = document.cookie,
cookieMap = {},
tmp,
cur,
len;
if(cookie) {
tmp = cookie.split(';');
len = tmp.length;
while(len--) {
cur = tmp[len];
if(cur) {
cur = cur.trim();
cur = cur.split('=');
cookieMap[cur[0]] = cur[1];
}
}
}
return cookieMap;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment