Get all cookies on my site

how can i get all cookies set by my website using js. I donโ€™t want to say Cookie ("username") , but iterate over all the cookies and get the key = value pairs of my site.

+4
source share
4 answers
var cookies = document.cookie.split(/;/); for (var i = 0, len = cookies.length; i < len; i++) { var cookie = cookies[i].split(/=/); alert("key: " + cookie[0] + ", value: " + cookie[1]); } 
+2
source

You can use getCookie from my answer to javascript getCookie functions and break it into getCookies and getCookie functions, where the getCookies function simply returns cookies instead of cookies[name] . And for the getCookie function getCookie just take the return value of getCookies and use [name] on it.


Update Ok, I just added features as described above. :)

+2
source

Please read on how to read / write cookies in JavaScript.

http://www.quirksmode.org/js/cookies.html

You might be looking for a solution like this: Get all cookies with Javascript

The following function loads all cookie elements into an associative array with the cookie name as index and cookie value as value:

 function get_cookies_array() { var cookies = { }; if (document.cookie && document.cookie != '') { var split = document.cookie.split(';'); for (var i = 0; i < split.length; i++) { var name_value = split[i].split("="); name_value[0] = name_value[0].replace(/^ /, ''); cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]); } } return cookies; } 

After that, you can get the cookies and write them to the document as follows:

 var cookies = get_cookies_array(); for(var name in cookies) { document.write( name + " : " + cookies[name] + "<br />" ); } 
0
source
 <html> <head> <script type="text/javascript"> function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function checkCookie() { var username=getCookie("username"); if (username!=null && username!="") { alert("Welcome again " + username); } else { username=prompt("Please enter your name:",""); if (username!=null && username!="") { setCookie("username",username,365); } } } </script> </head> <body onload="checkCookie()"> </body> </html> 

copy paste from: http://www.w3schools.com/JS/js_cookies.asp

0
source

Source: https://habr.com/ru/post/1338700/


All Articles