Skip to content

Instantly share code, notes, and snippets.

@BenHall
Created January 19, 2012 17:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BenHall/1641205 to your computer and use it in GitHub Desktop.
Save BenHall/1641205 to your computer and use it in GitHub Desktop.
How to get/set a cookie in Javascript
// Taken from: https://developer.mozilla.org/en/DOM/document.cookie
// docCookies.setItem("test1", "Hello world!");
// alert(docCookies.getItem("test1"));
docCookies = {
getItem: function (sKey) {
if (!sKey || !this.hasItem(sKey)) { return null; }
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1"));
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/.test(sKey)) { return; }
var sExpires = "";
if (vEnd) {
switch (typeof vEnd) {
case "number": sExpires = "; max-age=" + vEnd; break;
case "string": sExpires = "; expires=" + vEnd; break;
case "object": if (vEnd.hasOwnProperty("toGMTString")) { sExpires = "; expires=" + vEnd.toGMTString(); } break;
}
}
document.cookie = escape(sKey) + "=" + escape(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
},
removeItem: function (sKey) {
if (!sKey || !this.hasItem(sKey)) { return; }
var oExpDate = new Date();
oExpDate.setDate(oExpDate.getDate() - 1);
document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";
},
hasItem: function (sKey) { return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment