根据MDN,设置为路径'/'are available anywhere in the same domain的cookie。 several different sources证实了这一点。
但是,我只是没有发现这种情况。我使用firefox在google.com
上的(不存在)目录上运行了以下测试:
> window.location = 'https://google.com/dir/file.html'
Navigated to https://google.com/dir/file.html
"https://google.com/dir/file.html"
> document.cookie
""
> document.cookie = 'key1=value1,path=/'
"key1=value1,path=/"
> document.cookie
"key1=value1,path=/"
> window.location = '/dir2/file.html'
Navigated to https://google.com/dir2/file.html
"/dir2/file.html"
> document.cookie
""
我误会了吗?我究竟做错了什么?我在Chrome上尝试了类似的测试,但结果相同。
答案 0 :(得分:0)
弄清楚了。我正在用逗号定界符而不是分号定界符设置path
。它是在我键入时按字面意思写Cookie,而不是解释路径和域。
写cookie的正确方法是document.cookie = 'key1=value1;path=/'
。