如何在 Javascript 中获取 cookie 的域值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2959010/
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 to get the domain value for a cookie in Javascript?
提问by Wabbitseason
Using Javascript I'd like to get the domainvalue for a specific cookie.
使用 Javascript 我想获取domain特定 cookie的值。
Is this possible? If so, how?
这可能吗?如果是这样,如何?
To clarify: I'm not looking for the valueof the cookie. I'm on "subdomain.domain.com" and I need to remove a cookie whose name is known but its domain value is something like ".domain.com". In short: I'd like to get the value of ".domain.com".
澄清一下:我不是在寻找cookie的价值。我在“subdomain.domain.com”上,我需要删除一个名称已知但其域值类似于“.domain.com”的cookie。简而言之:我想获得“.domain.com”的价值。
回答by bobince
Sorry, all you get is what you see in document.cookie. The cookie metadata like path, domainand expiresare not visible to site code (neither to JavaScript nor to the server-side).
抱歉,您得到的只是您在 中看到的内容document.cookie。cookie 元数据如path,domain并且expires对站点代码不可见(对 JavaScript 和服务器端均不可见)。
To read a cookie that is being shadowed by a cookie with a more-specific domainor path, the only thing you can do is load a page for which the more-specific cookie is out-of-scope, and read it from there.
要读取被具有更具体domain或cookie 的 cookie 覆盖的 cookie,path您唯一能做的就是加载一个更具体的 cookie 超出范围的页面,然后从那里读取它。
If, as you say, you only need to removea cookie, what you could do is try to remove the cookie at every possible level of specificity, eg.:
如果,如您所说,您只需要删除一个 cookie,您可以做的是尝试在每个可能的特定级别删除 cookie,例如:
document.cookie= 'foo=;domain=sub.domain.example.com;expires=Sat, 01-Jan-2000 00:00:00 GMT';
document.cookie= 'foo=;domain=domain.example.com;expires=Sat, 01-Jan-2000 00:00:00 GMT';
document.cookie= 'foo=;domain=example.com;expires=Sat, 01-Jan-2000 00:00:00 GMT';
and similarly with the pathvariable. You could put this in a nested loop for each path and domain part, splitting on .for the domain and /for the path.
与path变量类似。您可以将它放在每个路径和域部分的嵌套循环中,.为域和/路径拆分。
回答by Josh Stodola
You can only access cookies from the same domain (this includes subdomains). Obviously doing otherwise would be a security concern.
您只能访问来自同一域(包括子域)的 cookie。显然,否则将是一个安全问题。

