Skip to content

Instantly share code, notes, and snippets.

@InfamousStarFox
Last active May 28, 2022 18:00
Show Gist options
  • Save InfamousStarFox/cd246a19dcc3fec3d4e84176bb803e6d to your computer and use it in GitHub Desktop.
Save InfamousStarFox/cd246a19dcc3fec3d4e84176bb803e6d to your computer and use it in GitHub Desktop.
JavaScript cookie helper
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=/;secure';
},
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]);
});
}
}
@InfamousStarFox
Copy link
Author

Example Usage
cookie.set("myCookieName","myCookieValue");
cookie.get("myCookieName");
cookie.delete("myCookieName");
cookie.deleteAll();

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