如何使用 Javascript 列出当前页面的所有 cookie?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3400759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I list all cookies for the current page with Javascript?
提问by Speldosa
Is there any way to, with help of Javascript, list all cookies associated with the current page? That is, if I don't know the names of the cookies but want to retrieve all the information they contain.
有没有办法在 Javascript 的帮助下列出与当前页面关联的所有 cookie?也就是说,如果我不知道 cookie 的名称但想检索它们包含的所有信息。
回答by DixonD
You can list cookies for current domain:
您可以列出当前域的 cookie:
function listCookies() {
var theCookies = document.cookie.split(';');
var aString = '';
for (var i = 1 ; i <= theCookies.length; i++) {
aString += i + ' ' + theCookies[i-1] + "\n";
}
return aString;
}
But you cannot list cookies for other domains for security reasons
但出于安全原因,您不能列出其他域的 cookie
回答by Speldosa
var x = document.cookie;
window.alert(x);
This displays every cookie the current site has access to. If you for example have created two cookies "username=Frankenstein" and "username=Dracula", these two lines of code will display "username=Frankenstein; username=Dracula". However, information such as expiry date will not be shown.
这将显示当前站点有权访问的每个 cookie。例如,如果您创建了两个 cookie“username=Frankenstein”和“username=Dracula”,这两行代码将显示“username=Frankenstein;username=Dracula”。但是,不会显示到期日期等信息。
回答by Jayant Bhawal
Many people have already mentioned that document.cookiegets you all the cookies (except http-onlyones).
很多人已经提到,它document.cookie可以为您提供所有 cookie(除了 cookie http-only)。
I'll just add a snippet to keep up with the times.
我将添加一个片段以跟上时代的步伐。
document.cookie.split(';').reduce((cookies, cookie) => {
const [ name, value ] = cookie.split('=').map(c => c.trim());
cookies[name] = value;
return cookies;
}, {});
The snippet will return an object with cookie names as the keys with cookie values as the values.
该代码段将返回一个以 cookie 名称作为键,以 cookie 值作为值的对象。
Slightly different syntax:
语法略有不同:
document.cookie.split(';').reduce((cookies, cookie) => {
const [ name, value ] = cookie.split('=').map(c => c.trim());
return { ...cookies, [name]: value };
}, {});
回答by Yuval Adam
No.
不。
The only API browsers give you for handling cookies is getting and setting them via key-value pairs. All browsers handle cookies by domain nameonly.
唯一为您提供处理 cookie 的 API 浏览器是通过键值对获取和设置它们。所有浏览器仅通过域名处理 cookie 。
Accessing all cookies for current domain is done via document.cookie.
访问当前域的所有 cookie 是通过document.cookie.
回答by Paul Bishop
For just quickly viewing the cookies on any particular page, I keep a favorites-bar "Cookies" shortcut with the URL set to:
为了快速查看任何特定页面上的 cookie,我保留了一个收藏夹栏“cookies”快捷方式,并将 URL 设置为:
javascript:window.alert(document.cookie.split(';').join(';\r\n'));
回答by tur1ng
No there isn't. You can only read information associated with the current domain.
不,没有。您只能读取与当前域关联的信息。
回答by Fofaster
function listCookies() {
let cookies = document.cookie.split(';')
cookies.map((cookie, n) => console.log(`${n}:`, decodeURIComponent(cookie)))
}
function findCookie(e) {
let cookies = document.cookie.split(';')
cookies.map((cookie, n) => cookie.includes(e) && console.log(decodeURIComponent(cookie), n))
}
This is specifically for the window you're in. Tried to keep it clean and concise.
这是专门为您所在的窗口设计的。尽量保持简洁。
回答by Travis J
Some cookies, such as referrer urls, have =in them. As a result, simply splitting on =will cause irregular results, and the previous answers here will breakdown over time (or immediately depending on your depth of use).
某些 cookie,例如引荐来源网址,包含=在其中。因此,简单地拆分=会导致不规则的结果,并且这里以前的答案会随着时间的推移而崩溃(或立即取决于您的使用深度)。
This takes only the first instance of the equals sign. It returns an object with the cookie's key value pairs.
这仅需要等号的第一个实例。它返回一个带有 cookie 键值对的对象。
// Returns an object of key value pairs for this page's cookies
function getPageCookies(){
// cookie is a string containing a semicolon-separated list, this split puts it into an array
var cookieArr = document.cookie.split(";");
// This object will hold all of the key value pairs
var cookieObj = {};
// Iterate the array of flat cookies to get their key value pair
for(var i = 0; i < cookieArr.length; i++){
// Remove the standardized whitespace
var cookieSeg = cookieArr[i].trim();
// Index of the split between key and value
var firstEq = cookieSeg.indexOf("=");
// Assignments
var name = cookieSeg.substr(0,firstEq);
var value = cookieSeg.substr(firstEq+1);
cookieObj[name] = value;
}
return cookieObj;
}

