Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting persistent cookies with javascript

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

like image 929
SAFAD Avatar asked Jan 04 '12 19:01

SAFAD


People also ask

What is persistent cookie in JavaScript?

Persistent cookiePersistent cookies are not deleted by the browser when the user closes it. These cookies have an expiration date that you can set in your server. You can set a cookie to expire in a day or ten years.

Can you set cookies with JavaScript?

JavaScript can create, read, and delete cookies with the document.

How do you make a permanent cookie?

Permanent cookies are available until a specified expiration date, and are stored on the hard disk.So Set the 'Expires' property any value greater than DataTime. MinValue with respect to the current datetime. If u want the cookie which never expires set its Expires property equal to DateTime. maxValue.

Can secure cookies be read by JavaScript?

Known as the "secure flag" Secure as in the cookie cannot be read by Javascript running in the browser — ie. document. cookie will not work.


1 Answers

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)

like image 64
pete Avatar answered Sep 18 '22 15:09

pete