在域上创建JavaScript Cookie并跨子域阅读 [英] Creating a javascript cookie on a domain and reading it across sub domains

查看:147
本文介绍了在域上创建JavaScript Cookie并跨子域阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是在用户的计算机上写入12个月的Javascript Cookie。

Below is a Javascript cookie that is written on the user's computer for 12 months.

在我们的主域上设置cookie,例如 example.com ,如果用户访问 test.example.com 的子域,我们需要继续标识用户的活动

After we set the cookie on our main domain such as example.com, should the user visit a subdomain like test.example.com, we need to continue to identify the activity of the user across our "test" subdomain.

但是对于当前的代码,只要他们离开 www.example.com 并访问 test.example.com ,它们不再标记为HelloWorld。

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?

Would anyone be able to help with my code to allow the cookie to be read across subdomains?

<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>


推荐答案

只需设置 / code>和路径属性,例如:

<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>

这篇关于在域上创建JavaScript Cookie并跨子域阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆