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

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

问题描述

以下是在用户计算机上写入 12 个月的 JavaScript cookie.

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

在我们的主域(例如 example.com)上设置 cookie 后,如果用户访问像 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>

推荐答案

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

Just set the domain and path attributes on your cookie, like:

<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天全站免登陆