Skip to content

Instantly share code, notes, and snippets.

@relliv
Forked from InfamousStarFox/cookies.js
Last active May 28, 2022 18:01
Show Gist options
  • Save relliv/8044c3c41d2ce75fd0534b630a475ec7 to your computer and use it in GitHub Desktop.
Save relliv/8044c3c41d2ce75fd0534b630a475ec7 to your computer and use it in GitHub Desktop.
JavaScript cookie helper
/**
* Cookie utility
*
* @source https://gist.github.com/InfamousStarFox/cd246a19dcc3fec3d4e84176bb803e6d
*/
var cookie = {
get: function (cookieName) {
var cookie = document.cookie.split(";").find(function (item) {
return item.trim().startsWith(cookieName + '=');
});
return cookie ? decodeURIComponent(cookie?.split('=')[1]) : '';
},
set: function (cookieName, cookieValue) {
var cookieDate = new Date;
cookieDate.setFullYear(cookieDate.getFullYear() + 10);
document.cookie = cookieName + '=' + encodeURIComponent(cookieValue) + ';expires=' + cookieDate.toUTCString() + ';path=/';
},
delete: function (cookieName) {
document.cookie = cookieName + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;secure';
},
deleteAll: function () {
document.cookie.split(";").forEach(function (item) {
cookie.delete(item.trim().split('=')[0]);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment