使用 javascript 设置持久性 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8733025/
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 persistent cookies with javascript
提问by SAFAD
I have found a weird bug in my application and due to my small experience with Javascript I couldn't debug it;
我在我的应用程序中发现了一个奇怪的错误,由于我对 Javascript 的经验很少,我无法调试它;
I am trying to set a persistent cookie, which will die after one year from its set (max value in major browsers) but persists and won't be deleted after the browser gets closed. I've been using this code:
我正在尝试设置一个持久性 cookie,该 cookie 将在其设置一年后消失(主要浏览器中的最大值),但在浏览器关闭后仍然存在且不会被删除。我一直在使用这个代码:
// Build the expiration date string:
var expiration_date = new Date();
expiration_date.setYear (expiration_date.getYear () + 1);
expiration_date = expiration_date.toGMTString();
// Build the set-cookie string:
var cookie_string = "test_cookies = true; path=/; expires=" + expiration_date;
// Create/update the cookie:
document.cookie = cookie_string;
I've noticed that the cookie has a session tag when I use cookie manager plugin, and only the ones with this tag get removed when the browser shuts down (others like Wordpress's and such scripts persist).
我注意到,当我使用 cookie 管理器插件时,cookie 有一个会话标签,当浏览器关闭时,只有带有此标签的 cookie 才会被删除(其他像 Wordpress 和此类脚本的脚本仍然存在)。
回答by pete
I changed your syntax over to my style of coding (variables at the top, minimal re-casting, etc.) and the example below works on my localhost quite well.
我将您的语法更改为我的编码风格(顶部的变量、最少的重铸等),下面的示例在我的本地主机上运行良好。
// Build the expiration date string:
var expiration_date = new Date();
var cookie_string = '';
expiration_date.setFullYear(expiration_date.getFullYear() + 1);
// Build the set-cookie string:
cookie_string = "test_cookies=true; path=/; expires=" + expiration_date.toUTCString();
// Create or update the cookie:
document.cookie = cookie_string;
If you are having problems on a production server, try setting the domain of the cookie as well (www.quirksmode.org/js/cookies.html#link5)
如果您在生产服务器上遇到问题,请尝试设置 cookie 的域(www.quirksmode.org/js/cookies.html#link5)
回答by keeganwatkins
回答by vivek nuna
You can also use the max-age
attribute.
您也可以使用该max-age
属性。
cookie_string = "test_cookies=true; path=/; max-age=31536000";
- One week: max-age=604800
- One month: max-age=2628000
- One year: max-age=31536000
- 一周:max-age=604800
- 一个月:max-age=2628000
- 一年:max-age=31536000