Javascript 使用javascript设置跨子域cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4713019/
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
setting cross-subdomain cookie with javascript
提问by newnomad
How should I add domain support to thesefunctions? I want to achieve that .example.com is declared as domain, so that the cookies can be read across all subdomains of the example.com. In its current form since domain is not set, it can only be read from www.example.com
我应该如何为这些功能添加域支持?我想实现将 .example.com 声明为域,以便可以跨 example.com 的所有子域读取 cookie。由于未设置域,因此目前的形式只能从 www.example.com 读取
回答by Tom Gullen
Here is a link on how to share cookies amongst a domain:
这是有关如何在域之间共享 cookie 的链接:
https://www.thoughtco.com/javascript-by-example-2037272
https://www.thoughtco.com/javascript-by-example-2037272
It involves setting the domain attribute of the cookie string like:
它涉及设置 cookie 字符串的域属性,如:
document.cookie = "myValue=5;path=/;domain=example.com";
This cookie should now be accessible to all sub domains of example.com like login.example.com
此 cookie 现在应该可供 example.com 的所有子域访问,例如 login.example.com
回答by stujo
In my case we needed to set a cookie that would work across our .com subdomains:
在我的例子中,我们需要设置一个可以在我们的 .com 子域中工作的 cookie:
function setCrossSubdomainCookie(name, value, days) {
const assign = name + "=" + escape(value) + ";";
const d = new Date();
d.setTime(d.getTime() + (days*24*60*60*1000));
const expires = "expires="+ d.toUTCString() + ";";
const path = "path=/;";
const domain = "domain=" + (document.domain.match(/[^\.]*\.[^.]*$/)[0]) + ";";
document.cookie = assign + expires + path + domain;
}
This might not work for .co.uk etc but the principle can be used
这可能不适用于 .co.uk 等,但可以使用该原理