Reputation: 624
I can't seem to set cookies with short lifespans in Google Chrome. They're either not getting set, or are immediately being deleted (can't tell which, although the result is the same either way). This only occurs if the expiration is 4 hours or less in the future. Identical code works fine if the expiration time is greater than 4 hours and the issue does not occur in Firefox or Safari. Here's an example:
Does not work:
exp = new Date();
exp.setMinutes(exp.getMinutes() + 240);
document.cookie="name=value;expires=" + exp + ";path=/";
Works:
exp = new Date();
exp.setMinutes(exp.getMinutes() + 241);
document.cookie="name=value;expires=" + exp + ";path=/";
Does anyone have any suggestions for how to resolve this?
Upvotes: 4
Views: 2764
Reputation: 4686
Indeed I checked out the Chromium Source here http://code.google.com/p/chromium/source/search?q=document.cookie+expire&origq=document.cookie+expire&btnG=Search+Trunk with reference to cookies and found in all their expires= statements they call either .toGMTString() or .toUTCString() on a date object so it might be a peculiar Date Formatting function screwing up when it imlpicitly converts it to a format rather than explictly setting one.?!
instead of this:
document.cookie="name=value;expires=" + exp + ";path=/";
try this:
document.cookie="name=value;expires=" + exp.toUTCString() + ";path=/";
Upvotes: 3
Reputation: 656
Seems to work for me using jQuery.cookie:
Command: exp = new Date()
Output: Thu Aug 09 2012 11:39:21 GMT-0700 (Pacific Daylight Time)
Command: exp.setMinutes(exp.getMinutes() + 240)
Output: 1344551961739
Command: $.cookie('testCookie', 'test', {path: '/', expires: exp});
Output: "testCookie=test; expires=Thu, 09 Aug 2012 22:39:21 GMT; path=/"
This was done in Chrome's console on windows.
Note: 22:39 in GMT is 15:39 in GMT -0700 so it is a 4 hour expiration.
Edit: I tested your code directly and it doesn't seem to accept the cookie being set to expire in less than 4 hours. This doesn't use jQuery:
exp = new Date();
exp.setMinutes(exp.getMinutes() + 240);
document.cookie="testCookie2=test;expires=" + exp.toUTCString() + ";path=/";
Upvotes: 1