Skip to content

Instantly share code, notes, and snippets.

@jrivero
Last active February 21, 2024 11:36
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jrivero/949141 to your computer and use it in GitHub Desktop.
Save jrivero/949141 to your computer and use it in GitHub Desktop.
Pure Javascript Cookies Management
// found on http://snipplr.com/view/36790/jscookies--my-simple-easy-pure-js-javascript-cookies-function/
// create my jsCookies function
var jsCookies = {
// this gets a cookie and returns the cookies value, if no cookies it returns blank ""
get: function(c_name) {
if (document.cookie.length > 0) {
var c_start = document.cookie.indexOf(c_name + "=");
if (c_start != -1) {
c_start = c_start + c_name.length + 1;
var c_end = document.cookie.indexOf(";", c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
return unescape(document.cookie.substring(c_start, c_end));
}
}
return "";
},
// this sets a cookie with your given ("cookie name", "cookie value", "good for x days")
set: function(c_name, value, expiredays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + expiredays);
document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString());
},
// this checks to see if a cookie exists, then returns true or false
check: function(c_name) {
c_name = jsCookies.get(c_name);
if (c_name != null && c_name != "") {
return true;
} else {
return false;
}
}
};
// end my jsCookies function
// USAGE - get :: jsCookies.get("cookie_name_here"); [returns the value of the cookie]
// USAGE - set :: jsCookies.set("cookie_name", "cookie_value", 5 ); [give name, val and # of days til expiration]
// USAGE - check :: jsCookies.check("cookie_name_here"); [returns only true or false if the cookie exists or not]
@max107
Copy link

max107 commented Nov 21, 2013

Replace 32 line to

return c_name != null && c_name != "";

@dubrod
Copy link

dubrod commented Nov 13, 2015

i used your script before and it was fine but now it seems to be setting individual cookies per page. tested in firefox and chrome. I was setting a cookie on page2 but page3 wouldnt see it.

I changed this line 26:

document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toUTCString()) + "; path=/";

and its now a global sitewide cookie.

@fercarvo
Copy link

You have to use some ES6 syntaxis, visit my gist version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment