有两个域: a.example.com example.com
example.com 是 a.example.com 的父域。现在, a.example.com 和 example.com 都可以编写名为 test_cookie 的Cookie。现在我们有一个 a.example.com 页面,它将使用javascript来读取cookie test_cookie 的值。有没有办法只读取 a.example.com 域中设置的cookie而不是 example.com ?
也许我的问题有点不清楚,
我想要实现的目标是: 1.我想写一个名为 readCookie 的函数来读取名为 test_cookie 的cookie,其中: 一个。当域 example.com 下有一个cookie: test_cookie ,域 a.example.com test_cookie >,readCookie返回null 湾当域名 example.com 下有cookie时 test_cookie 而域名 a.example.com 下的Cookie test_cookie strong>,readCookie返回域 a.example.com 下的Cookie值 C。如果 exampler.com 下没有Cookie: test_cookie ,但域 a.example.com >下有一个Cookie test_cookie strong>,readCookie返回域 a.example.com 下的Cookie值。
答案 0 :(得分:11)
这取决于cookie的定义方式,特别是如果 Domain 属性指定了它具有的值(参见RFC 2965 – User Agent Role):
.
.example.com
开头(如果不是,例如example.com
,它将被更改用户代理.example.com
)。现在,Cookie的域名必须domain-match在请求中发送的域名。情况就是这样:
这意味着:
effective domain | example.com | a.example.com | foo.example.com | bar.a.example.com
------------------+-------------+---------------+-----------------+-------------------
example.com | ✓ | ✗ | ✗ | ✗
a.example.com | ✗ | ✓ | ✗ | ✗
.example.com | ✓ | ✓ | ✓ | ✓
.a.example.com | ✗ | ✓ | ✗ | ✓
因此,如果您希望Cookie仅对 a.example.com 有效,则要么省略域属性,要么指定域属性为.a.example.com
(这会使Cookie对 a.example.com 及其子域有效)。
答案 1 :(得分:3)
只能通过设置example.com
参数,无法将Cookie限制为domain
。但是,在大多数浏览器中,只有在未提供example.com
的情况下,Cookie才会默认为domain
。不幸的是,在IE中它默认允许子域访问cookie。
这就是您将主网站放在www.example.com
而不只是example.com
的原因。使用主域example.com
上的网站,您无法可靠地将Cookie分开。