javascript cookie 的最大生命周期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10328361/
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
Maximum LifeTime of javascript cookie
提问by asura
What can be the maximum acceptable expiry-time value of Javascript persistence cookie?
Javascript 持久性 cookie 的最大可接受到期时间值是多少?
采纳答案by Pranay Rana
Read: Expires and Max-Age of Cookies
Life time of the javascript cookies is depend on what amount of time you set when creating cookies for example following set the life time of 10 minutes
javascript cookie 的生命周期取决于您在创建 cookie 时设置的时间,例如将生命周期设置为 10 分钟
expiry = new Date();
expiry.setTime(date.getTime()+(10*60*1000));
// Ten minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "visited=yes; expires=" + expiry.toGMTString();
there is no way that you can set the life time coookie...i.e cookie with no expiration
没有办法设置cookie的生命周期......即cookie没有过期
回答by Mike Scott
Forever cookie: Possible if you re-write the cookie every time you read it, setting the expire date to some ridiculous date in the future eg: 10 yrs hence.
永远的 cookie:如果您每次阅读时都重写 cookie,将过期日期设置为未来某个荒谬的日期,例如:10 年后,则可能。
For that to not be forever you are assuming the web page will not be read for more than 10 years, in which case what's the point. You think we will still be using cookies in 10 yrs :-)
为了不是永远,你假设网页不会被阅读超过 10 年,在这种情况下有什么意义。您认为 10 年后我们仍会使用 cookie :-)
Plus a cookie longevity is only as long as the hardware its stored on. Will you be using the same hardware in 10 yrs?
此外,cookie 的寿命仅与其存储的硬件一样长。您会在 10 年后使用相同的硬件吗?
Note: read cookie then immediately write same cookie I found was problematic on some computers (reason unknown). Fix was embed the write cookie in a timeout:
注意:读取cookie然后立即写入我发现在某些计算机上有问题的相同cookie(原因未知)。修复在超时中嵌入写入 cookie:
var x=getCookie('mycookie');
setTimeout('saveCookie("mycookie", x)',1000)
getCookie and saveCookie being functions you have to create in this example, and saveCookie function sets cookie life at 10 yrs
getCookie 和 saveCookie 是您必须在此示例中创建的函数,而 saveCookie 函数将 cookie 寿命设置为 10 年
At the speed of technology evolution, that's 'forever' :-)
以技术发展的速度,那是“永远的”:-)
回答by Harrison Smith
Using the maximum milliseconds-since-the-epoch
value, an expiry date can be generated which represents the "longest possible time" for a cookie to be kept alive.
使用最大值milliseconds-since-the-epoch
,可以生成表示 cookie 保持活动的“最长可能时间”的到期日期。
var key = 'foo';
var value = 'bar';
var expiryDate = new Date(8640000000000000).toUTCString();
var cookie = `${key}=${value};expires=${expiryDate}`;
console.log(cookie);