Skip to content

Instantly share code, notes, and snippets.

@wwsun
Created May 12, 2015 01:29
Show Gist options
  • Save wwsun/f14f0468a8173d6d6781 to your computer and use it in GitHub Desktop.
Save wwsun/f14f0468a8173d6d6781 to your computer and use it in GitHub Desktop.
cookie utility object to get/set/unset the cookie pair
var CookieUtil = {
get: function (name) {
var cookieName = encodeURIComponent(name) + "=",
cookieStart = document.cookie.indexOf(cookieName),
cookieValue = null;
if (cookieStart > -1) {
var cookieEnd = document.cookie.indexOf(";", cookieStart);
if (cookieEnd == -1) {
cookieEnd = document.cookie.length;
}
cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
}
return cookieValue;
},
set: function (name, value, expires, path, domain, secure) {
var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
if (expires instanceof Date) {
cookieText += "; expires=" + expires.toUTCString();
}
if (path) {
cookieText += "; path=" + path;
}
if (domain) {
cookieText += "; domain=" + domain;
}
if (secure) {
cookieText += "; secure";
}
document.cookie = cookieText;
},
unset: function (name, path, domain, secure) {
this.set(name, "", new Date(0), path, domain, secure);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment