0

So I am quite new to cookies and I was wondering why this doesn't work to read cookie data?

//How to sort through the cookies
document.cookie = "key1=value1; key2=value2";
console.log(document.cookie);
//Makes an array of the Cookies
let pairs = document.cookie.split(";");
//Dictionary
let cookieDictionary={};

//Loops through the cookies and assigns them to a dictionary.
for(p of pairs)
{
    let vals = p.split("=");
    cookieDictionary[vals[0]] = vals[1];
}
//Create a key for easy cookie lookup
let cookieKeys = Object.keys(cookieDictionary);
console.log(cookieKeys);
sonyansachdev
  • 97
  • 1
  • 2
  • 5

1 Answers1

2

You can only set one cookie at the time

So instead of

document.cookie = "key1=value1; key2=value2";

you should be doing

document.cookie = "key1=value1";
document.cookie = "key2=value2";

The entire script should then be something like

//How to sort through the cookies
document.cookie = "key1=value1"; 
document.cookie = "key2=value2";


console.log(document.cookie);
//Makes an array of the Cookies
let pairs = document.cookie.split(";");
//Dictionary
let cookieDictionary={};

//Loops through the cookies and assigns them to a dictionary.
for(p of pairs)
{
    let vals = p.split("=");
    cookieDictionary[vals[0]] = vals[1];
}
//Create a key for easy cookie lookup
let cookieKeys = Object.keys(cookieDictionary);
console.log(cookieKeys);

Like in this jsfiddle https://jsfiddle.net/tzr5b6s4/1/

MDN: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

And there is a really nice SO post here Set cookie and get cookie with JavaScript

MikNiller
  • 1,242
  • 11
  • 17