Javascript Cookie with no expiration date

前端 未结 9 882

I would like to set up a cookie that never expires. Would that even be possible?

 document.cookie = \"name=value; expires=date; path=path;domain=domain; secu         


        
相关标签:
9条回答
  • 2020-11-27 13:55

    If you don't set an expiration date the cookie will expire at the end of the user's session. I recommend using the date right before unix epoch time will extend passed a 32-bit integer. To put that in the cookie you would use document.cookie = "randomCookie=true; expires=Tue, 19 Jan 2038 03:14:07 UTC;, assuming that randomCookie is the cookie you are setting and true is it's respective value.

    0 讨论(0)
  • 2020-11-27 13:56

    If you intend to read the data only from the client-side, you can use the local storage. It's deleted only when the browser's cache is cleared.

    0 讨论(0)
  • 2020-11-27 13:57

    You can make a cookie never end by setting it to whatever date plus one more than the current year like this :

    var d = new Date();    
    document.cookie = "username=John Doe; expires=Thu, 18 Dec " + (d.getFullYear() + 1) + " 12:00:00 UTC";
    
    0 讨论(0)
  • 2020-11-27 14:03

    You can do as the example on Mozilla docs:

     document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";
    

    P.S

    Of course, there will be an issue if humanity still uses your code on the first minute of year 10000 :)

    0 讨论(0)
  • 2020-11-27 14:07

    All cookies expire as per the cookie specification, Maximum value you can set is

     2^31 - 1 = 2147483647 = 2038-01-19 04:14:07
    

    So Maximum cookie life time is

    $.cookie('subscripted_24', true, { expires: 2147483647 });
    
    0 讨论(0)
  • 2020-11-27 14:09

    Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.

    0 讨论(0)
提交回复
热议问题