在域上创建 JavaScript cookie 并跨子域读取它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5671451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a JavaScript cookie on a domain and reading it across sub domains
提问by Evan
Below is a JavaScript cookie that is written on the user's computer for 12 months.
以下是在用户计算机上写入 12 个月的 JavaScript cookie。
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.
在我们的主域(例如 )上设置 cookie 之后example.com
,如果用户访问子域(例如 )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".
但是使用当前代码,一旦他们离开www.example.com
并访问test.example.com
,他们就不再被标记为“HelloWorld”。
Would anyone be able to help with my code to allow the cookie to be read across subdomains?
任何人都可以帮助我的代码以允许跨子域读取 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>
回答by aroth
Just set the domain
and path
attributes on your cookie, like:
只需在您的 cookie 上设置domain
和path
属性,例如:
<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>
回答by Mike Lewis
You want:
你要:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
根据RFC 2109,要让所有子域都可以使用 cookie,您必须.
在域前放置一个。
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
设置 path=/ 将使 cookie 在整个指定域(又名.example.com
)中可用。
回答by caseyjustus
Here is a working example :
这是一个工作示例:
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.
这是一个通用的解决方案,它从位置对象中获取根域并设置 cookie。反过来是因为您不知道您有多少个子域(如果有)。
回答by rebagliatte
You can also use the MDN JavaScript Cookie Frameworkand do:
您还可以使用MDN JavaScript Cookie 框架并执行以下操作:
docCookies.setItem('HelloWorld', 'HelloWorld', myDate, '/', 'example.com');