Skip to content

Instantly share code, notes, and snippets.

@fercarvo
Forked from jrivero/jsCookies.js
Last active February 21, 2024 11:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fercarvo/74490a37e26f978660efb02994a04987 to your computer and use it in GitHub Desktop.
Save fercarvo/74490a37e26f978660efb02994a04987 to your computer and use it in GitHub Desktop.
Pure Javascript Cookies Management
class Cookies {
static get (name) {
if (document.cookie.length === 0)
return null;
var c_start = document.cookie.indexOf(`${name}=`);
if (c_start === -1)
return null;
c_start = c_start + name.length + 1;
var c_end = document.cookie.indexOf(';', c_start);
if (c_end == -1)
c_end = document.cookie.length;
return decodeURIComponent( document.cookie.substring(c_start, c_end) );
}
static set (name, value, days) {
if (days > 0) {
let seconds = new Date().getTime() + 1000*60*60*24*days;
let date = new Date(seconds).toUTCString();
document.cookie = name + `=${encodeURIComponent(value)}; expires=${date}; path=/`;
} else {
document.cookie = name + `=${encodeURIComponent(value)}; path=/`
}
}
static remove (name) {
if (name)
document.cookie = name + `=''; expires=${new Date(1).toUTCString()}`;
}
static getAll () {
if (document.cookie.length === 0)
return null;
var cookies = {};
document.cookie.split(';').forEach(pairs => {
let pair = pairs.split('=');
cookies[ (pair[0]+'').trim() ] = decodeURIComponent(pair[1])
})
return cookies
}
static check (name) {
name = this.get(name);
return (name && name !== '') ? true : false;
}
}
// end Cookies Class
// USAGE - remove :: Cookies.remove("cookie_name"); [delete the cookie with that key]
// USAGE - get :: Cookies.get("cookie_name_here"); [returns the value of the cookie]
// USAGE - set :: Cookies.set("cookie_name", "cookie_value", 5 ); [give name, val and # of days til expiration]
// USAGE - check :: Cookies.check("cookie_name_here"); [returns only true or false if the cookie exists or not]
// USAGE - getAll :: Cookies.getAll(); [returns object with key value cookie]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment