有两个域: 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 而不是 example.com 域中设置的 cookie?
也许我的问题有点不清楚,
我想达到的目标是: 1. 我想编写一个名为 readCookie 的函数来读取名为 test_cookie 的 cookie,其中: 一种。当有 cookie 时:test_cookie 在域 example.com 下并且在域 a.example.com 下没有 cookie test_cookie>, readCookie 返回 null b.当有 cookie 时:test_cookie 在域 example.com 下,还有一个 cookie test_cookie 在域 a.example.com下strong>,readCookie返回域a.example.com下的cookie值 C。当 exampler.com 下没有 cookie: test_cookie,但域 a.example.com下有一个 cookie test_cookie strong>,readCookie 返回域 a.example.com 下的 cookie 值。
最佳答案
这取决于 cookie 的定义方式,特别是如果 Domain 属性指定了它具有的值(参见 RFC 2965 – User Agent Role ):
- 如果缺少Domain 属性,则用户代理假定为当前主机;否则
- 如果设置了 Domain 属性,它的值必须以
.
开头,例如.example.com
(如果没有,例如example.com
,它将被用户代理更改为.example.com
)。
现在一个cookie的域必须domain-match要在请求中发送的域。就是这样:
- 如果域相同(以防 Domain 参数丢失),或者
- 如果 Domain 属性中指定的值必须是域的后缀。
这意味着:
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 有效,您要么省略 Domain 属性,要么指定 Domain 属性与 .a.example.com
(这将使 cookie 对 a.example.com 及其子域有效)。
关于javascript - 我只能从二级域获取 cookie 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3566832/