Skip to content

Instantly share code, notes, and snippets.

@jesusalber1
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesusalber1/a937cdde33603f63ce26 to your computer and use it in GitHub Desktop.
Save jesusalber1/a937cdde33603f63ce26 to your computer and use it in GitHub Desktop.
Get and set cookies
/* Get and set cookies 'manually' */
function setCookie(cookieName, value, expirationYears) {
var CookieDate = new Date;
CookieDate.setFullYear(CookieDate.getFullYear() + expirationYears);
document.cookie = cookieName + '=' + value + '; expires=' + CookieDate.toGMTString( ) + ';';
}
function getCookie(cookieName) {
var currentCookie,
cookies = document.cookie.split('; '); /* Get all my cookies */
for (var i = 0; i < cookies.length; i++){
currentCookie = cookies[i].split('='); /* [ cookieName, value ] */
if(currentCookie[0] === cookieName){
return currentCookie[1]; /* cookieValue = currentCookie[1] */
}
}
}
/* Returns an object like: (Not an Array, Why? I want to identify later each cookie...)
{
cookieName1: cookieValue1,
cookieName2: cookieValue2,
...
}
*/
function getAllCookies() {
var allCookies = {},
currentCookie,
cookies = document.cookie.split('; '); /* Get all my cookies */
for (var i = 0; i < cookies.length; i++){
currentCookie = cookies[i].split('='); /* [ cookieName, cookieValue ] */
allCookies[currentCookie[0]] = currentCookie[1]; /* { cookieName: cookieValue } */
}
return allCookies;
}
/*
setCookie('mycookie', 'mycookievalue', 1);
getCookie('mycookie');
getAllCookies();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment