Reputation:
I need to get all the cookies stored in my browser using JavaScript. How can it be done?
Upvotes: 137
Views: 317732
Reputation: 931
What you are asking is possible; but that will only work on a specific browser. You have to develop a browser extension app to achieve this. You can read more about chrome api to understand better. https://developer.chrome.com/extensions/cookies
Upvotes: 0
Reputation: 5090
If you develop browser extensions you can try browser.cookies.getAll()
Upvotes: 1
Reputation: 11205
You can only access cookies for a specific site. Using document.cookie
you will get a list of escaped key=value pairs seperated by a semicolon.
secret=do%20not%20tell%you;last_visit=1225445171794
To simplify the access, you have to parse the string and unescape all entries:
var getCookies = function(){
var pairs = document.cookie.split(";");
var cookies = {};
for (var i=0; i<pairs.length; i++){
var pair = pairs[i].split("=");
cookies[(pair[0]+'').trim()] = unescape(pair.slice(1).join('='));
}
return cookies;
}
So you might later write:
var myCookies = getCookies();
alert(myCookies.secret); // "do not tell you"
Upvotes: 118
Reputation: 76011
HttpOnly
cookies.document.cookie
property, which contains a semicolon separated list of name=value
pairs.Upvotes: 65
Reputation: 136
Added trim() to the key in object, and name it str, so it would be more clear that we are dealing with string here.
export const getAllCookies = () => document.cookie.split(';').reduce((ac, str) => Object.assign(ac, {[str.split('=')[0].trim()]: str.split('=')[1]}), {});
Upvotes: 4
Reputation: 1223
Modern approach.
let c = document.cookie.split(";").reduce( (ac, cv, i) => Object.assign(ac, {[cv.split('=')[0]]: cv.split('=')[1]}), {});
console.log(c);
;)
Upvotes: 4
Reputation: 4772
Since the title didn't specify that it has to be programmatic I'll assume that it was a genuine debugging/privacy management issue and solution is browser dependent and requires a browser with built in detailed cookie management toll and/or a debugging module or a plug-in/extension. I'm going to list one and ask other people to write up on browsers they know in detail and please be precise with versions.
Chromium, Iron build (SRWare Iron 4.0.280)
The wrench(tool) menu: Options / Under The Hood / [Show cookies and website permissions] For related domains/sites type the suffix into the search box (like .foo.tv). Caveat: when you have a node (site or cookie) click-highlighted only use [Remove] to kill specific subtrees. Using [Remove All] will still delete cookies for all sites selected by search and waste your debugging session.
Upvotes: 3
Reputation: 41152
You cannot. By design, for security purpose, you can access only the cookies set by your site. StackOverflow can't see the cookies set by UserVoice nor those set by Amazon.
Upvotes: 41
Reputation: 3393
To retrieve all cookies for the current document open in the browser, you again use the document.cookie
property.
Upvotes: 13