如何在 Javascript 中获取 cookie 的域值? [英] How to get the domain value for a cookie in Javascript?

查看:56
本文介绍了如何在 Javascript 中获取 cookie 的域值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Javascript 我想获取特定 cookie 的 domain 值.

这可能吗?如果是,怎么办?

澄清:我不是在寻找 cookie 的.我在subdomain.domain.com"上,我需要删除一个名称已知但其域值类似于.domain.com"的cookie.简而言之:我想获取.domain.com"的值.

解决方案

抱歉,您得到的只是您在 document.cookie 中看到的内容.pathdomainexpires 等 cookie 元数据对站点代码(JavaScript 和服务器端均不可见)不可见.

要读取被具有更具体的 domainpath 的 cookie 覆盖的 cookie,您唯一能做的就是加载一个页面更具体的 cookie 超出范围,请从那里读取.

如果,如您所说,您只需要删除一个 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';

path 变量类似.您可以将其放在每个路径和域部分的嵌套循环中,将 . 拆分为域,将 / 拆分为路径.

Using Javascript I'd like to get the domain value for a specific cookie.

Is this possible? If so, how?

To clarify: I'm not looking for the value of 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".

解决方案

Sorry, all you get is what you see in document.cookie. The cookie metadata like path, domain and expires are not visible to site code (neither to JavaScript nor to the server-side).

To read a cookie that is being shadowed by a cookie with a more-specific domain or 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.

If, as you say, you only need to remove a cookie, what you could do is try to remove the cookie at every possible level of specificity, eg.:

    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 path variable. You could put this in a nested loop for each path and domain part, splitting on . for the domain and / for the path.

这篇关于如何在 Javascript 中获取 cookie 的域值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆