Thursday, June 6, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  29] [ 3]  / answers: 1 / hits: 41833  / 13 Years ago, wed, january 4, 2012, 12:00:00

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 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:



// 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).


More From » cookies

 Answers
4

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)


[#88230] Tuesday, January 3, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mitchellg

Total Points: 235
Total Questions: 117
Total Answers: 106

Location: Fiji
Member since Wed, Jul 14, 2021
3 Years ago
;