javascript 为整个域而不是特定页面设置 cookie(使用 JS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26021281/
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
Set cookie (with JS) for whole domain not specific page
提问by Sheixt
I have a simple little script which I am using to set a cookie:
我有一个简单的小脚本,用于设置 cookie:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
The problem I have this cookie is only set on one page, not across the whole domain.
我有这个 cookie 的问题只设置在一个页面上,而不是整个域。
How can I adjust this function so that the cookie remains across the whole domain?
如何调整此功能以使 cookie 保留在整个域中?
回答by Wojciech Mleczek
You can specifiy domain ;domain=.example.com
as well as path ;path=/
("/" set cookie in whole domain)
您可以指定域;domain=.example.com
和路径;path=/
(“/”在整个域中设置 cookie)
document.cookie = cname + "=" + cvalue + "; " + expires +";path=/";