edt
edt

Reputation: 22440

In Chrome, how can I set a cookie with a max-age of less than 213 days?

Update: The solution was to restart my computer. I think the issue occurred because I changed my Windows date & time settings many times recently in order to do some testing. I think that must have thrown Chrome for a loop. Once I restarted, everything worked as expected.

When I try to set a cookie using JavaScript in Chrome with a max-age of less than 213 days, no cookie is set. My function seems to work fine in FireFox.

I'm not sure if I have an error in my setCookie function (below), or if Chrome is limiting me.

https://codepen.io/edtalmadge/pen/pxdqvK

function setCookie(name, value, days) {
  document.cookie =
    name + "=" + value + "; Max-Age=" + days * 86400 + "; path=/";
  console.log(document.cookie);
}

setCookie("foo", "123", 212); // no cookie set

setCookie("bar", "456", 213); // cookie is set

Upvotes: 1

Views: 1836

Answers (1)

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 19997

Your code did work for me on Chrome, but max-age has had quirks in the past. Perhaps, give expires a shot instead. You can also try lowercasing Max-Age to max-age as shown in the docs.

function setCookie(cname, cvalue, exdays) {
  var d = new Date();
  d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
  var expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

setCookie("foo", "123", 212);
setCookie("bar", "456", 213);

Upvotes: 1

Related Questions