Skip to content

Instantly share code, notes, and snippets.

@litodam
Last active March 19, 2021 23:38
Show Gist options
  • Save litodam/3048775 to your computer and use it in GitHub Desktop.
Save litodam/3048775 to your computer and use it in GitHub Desktop.
Cookies Helper in Javascript
function CookiesHelper() {}
// usage
// CookiesHelper.createCookie("myCookieUniqueName", value, 30);
// CookiesHelper.createCookie("myJsonCookieUniqueName", json, 30);
CookiesHelper.createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
// usage
// var value = CookiesHelper.readCookie("myCookieUniqueName");
// var json = JSON.parse(CookiesHelper.readCookie("myJsonCookieUniqueName");
CookiesHelper.readCookie = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
CookiesHelper.eraseCookie = function(name) {
createCookie(name, "", -1);
}
// usage
// createCookie("myCookieUniqueName", value, 30);
// createCookie("myJsonCookieUniqueName", json, 30);
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
// usage
// var value = readCookie("myCookieUniqueName");
// var json = JSON.parse(readCookie("myJsonCookieUniqueName");
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
@nerdyman
Copy link

nerdyman commented Feb 23, 2017

If anyone stumbles across this, toGMTString is now deprecated, toUTCString is recommended instead.

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