How do you set a cookie to be accessible across the entire domain in Javascript

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

I suppose there should be a way to set a cookie to be accessible from the entire domain nevermind from which directory you are setting the cookie.

Say in mypage.com/blue/index.php y set the cookie "colour=blue;" this way:

document.cookie = "colour" + "=" + "blue"      + "; expires=" + expireDate.toGMTString()      + "; path=/"; 

Using this code, the cookie retrieval function in mypage.com/home.php can't access the content of the cookie.

If it was just from first level directories that the cookie needs to be set, we would be ok by doing path=../ instead of path=/

But how do you go about writing generic code that sets a cookie that is accessible from any page in that domain not minding how deep in the file structure is the page the cookie is being set from?

回答1:

Use path just like you did, but set an additional ;-delimited attribute "domain". If you start the domain value with a . it will allow any subdomains (.example.com would effectively allow *.example.com).

Full documentation for the various cookie options here



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!