在域上创建 JavaScript cookie 并跨子域读取它

下面是一个在用户电脑上写了12个月的 JavaScript cookie。

在主域(如 example.com)上设置 cookie 之后,如果用户访问子域(如 test.example.com) ,我们需要继续识别用户在“测试”子域上的活动。

But with the current code, as soon as they leave www.example.com and visit test.example.com, they are no longer flagged as "HelloWorld".

是否有人能够帮助我的代码,以便允许在子域之间读取 cookie?

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate;
</script>
273672 次浏览

你想要:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

根据 RFC 2109,要让一个 cookie 对所有子域可用,您必须在域的前面放置一个 .

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

只需在 cookie 上设置 domainpath属性,比如:

<script type="text/javascript">
var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
+ ";domain=.example.com;path=/";
</script>

下面是一个可行的例子:

document.cookie = "testCookie=cookieval; domain=." +
location.hostname.split('.').reverse()[1] + "." +
location.hostname.split('.').reverse()[0] + "; path=/"

This is a generic solution that takes the root domain from the location object and sets the cookie. The reversing is because you don't know how many subdomains you have if any.

你亦可使用 饼干应用程序接口进行以下工作:

browser.cookies.set({
url: 'example.com',
name: 'HelloWorld',
value: 'HelloWorld',
expirationDate: myDate
}

方法文档