我在我的应用程序中发现了一个奇怪的错误,由于我对 Javascript 的经验不足,我无法调试它;
我正在尝试设置一个持久性 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;
我注意到当我使用 cookie 管理器插件时 cookie 有一个 session 标签,只有带有这个标签的标签在浏览器关闭时被删除(其他像 Wordpress 和这样的脚本仍然存在)。
最佳答案
我将您的语法更改为我的编码风格(顶部的变量、最少的重铸等),下面的示例在我的本地主机上运行良好。
// 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;
如果您在生产服务器上遇到问题,请尝试设置 cookie 的域 ( www.quirksmode.org/js/cookies.html#link5 )
关于javascript - 使用 javascript 设置持久性 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733025/