Setting persistent cookies with javascript

后端 未结 3 1441
广开言路
广开言路 2020-12-05 11:02

I have found a weird bug in my application and due to my small experience with Javascript I couldn\'t debug it;

I am trying to set a persistent cookie, which will d

相关标签:
3条回答
  • 2020-12-05 11:41

    You can also use the max-age attribute.

    cookie_string = "test_cookies=true; path=/; max-age=31536000";
    
    • One week: max-age=604800
    • One month: max-age=2628000
    • One year: max-age=31536000
    0 讨论(0)
  • 2020-12-05 11:51

    have you tried using the getFullYear() and setFullYear() methods of the Date instance instead of getYear() and setYear() ? the latter are are deprecated, see here.

    hope that helps! cheers.

    0 讨论(0)
  • 2020-12-05 11:55

    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)

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