Skip to content

Instantly share code, notes, and snippets.

@msereniti
Created November 19, 2018 07:30
Show Gist options
  • Save msereniti/28c2b368ce8df44b5ac3f44e6381e561 to your computer and use it in GitHub Desktop.
Save msereniti/28c2b368ce8df44b5ac3f44e6381e561 to your computer and use it in GitHub Desktop.
Very simple cookie handler, that has 2 methods: get cookie and set cookie. Based on functions from https://learn.javascript.ru/cookie (old, russian version of javascript.info)
const cookie = {
get: name => {
const matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
},
set: (name, value, options={}) => {
const expires = options.expires;
if (typeof expires == "number" && expires) {
const d = new Date();
d.setTime(d.getTime() + expires * 1000);
expires = options.expires = d;
}
if (expires && expires.toUTCString) {
options.expires = expires.toUTCString();
}
value = encodeURIComponent(value);
let updatedCookie = name + "=" + value;
for (let propName in options) {
updatedCookie += "; " + propName;
const propValue = options[propName];
if (propValue !== true) {
updatedCookie += "=" + propValue;
}
}
document.cookie = updatedCookie;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment