I'm trying to set multiple cookies in document.cookie
, but unfortunately only one is getting added.
I know there are multiple examples present on the 'Net for setting up these kind of cookies,and I followed one of them. But still I'm unable to set that out. I followed this link to set my cookie.
My Code:
function setCookie(start_time,end_session_time,total_time,flag,count){ var cookie_string = "start_time="+start_time;; if(end_session_time) { cookie_string +="; end_session_time="+end_session_time; } if(total_time){ cookie_string +="; total_time="+total_time; } if(flag){ cookie_string +="; flag="+flag; } if(count){ cookie_string +="; count="+count; } document.cookie =cookie_string ; console.log(cookie_string); console.log("document.cookie ="+ document.cookie); }
The Output:
cookie_string :: start_time=1369926508266; flag=1; count=1 document.cookie =start_time=1369926508266;
To store multiple key-value pairs in a cookie, you have to create a custom object, convert it to a JSON string with the help of the “stringify()” method, and store the resultant “document. cookie” object.
JavaScript can create, read, and delete cookies with the document.cookie property. With JavaScript, a cookie can be created like this: document.cookie = "username=John Doe"; You can also add an expiry date (in UTC time).
Serialize the custom object in a JSON string, parse it and then store in a cookie. For each name-value pair, use a separate cookie.
So, when accessing a cookie using client-side JavaScript, only the cookies that have the same domain as the one in the URL bar are accessible.
Adding a cookie is performed via document.cookie = "name=value"
to add multiple keys, you should perform multiple assigments
function setCookie(start_time, end_session_time, total_time, flag, count) { document.cookie = "start_time=" + start_time; if (end_session_time) { document.cookie = "end_session_time=" + end_session_time; } if (total_time) { document.cookie = "total_time=" + total_time; } if (flag) { document.cookie = "flag=" + flag; } if (count) { document.cookie = "count=" + count; } console.log("document.cookie = " + document.cookie); }
Cookies are key value pairs (with some optional additional info added on, like the expiry date). To set more than one, you just set document.cookie
more than once. The ;
separator is used to specify the additional info, not to add more different cookies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With