在域上创建JavaScript Cookie并跨子域阅读 [英] Creating a javascript cookie on a domain and reading it across sub domains
问题描述
以下是在用户的计算机上写入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屋!