0

I'm running on localhost on XAMPP. I am able to set the cookie, and see the result turn up in my Firefox as well as Chrome browser cookie management page. But whenever I close the browser, the cookie data is wiped clean even when the expiry date is set a month in advance. Below is my code:

$('#gen').on('click', function() {
    var data = "John";
    date = new Date();
    date.setMonth(date.getMonth()+1);
    document.cookie="name="+data;
    document.cookie="expires="+date;
});

Any comments would be much appreciated. Thank you for reading.

diggledoot
  • 691
  • 8
  • 22
  • 1
    When you say "on localhost" do you mean on a local webserver or do you mean `file://` URLs? – Pointy Apr 12 '20 at 12:55
  • file:// URL, does it count as as a local webserver if I'm running on XAMPP, @Pointy? – diggledoot Apr 12 '20 at 12:56
  • If it's `file://` URLs, then I suspect it's a security feature. Browsers generally consider every `file://` URL to be different domains from other files, and while I'm not positive I would not be surprised if that applied to the *same* file opened twice in succession. It's a security measure for stuff like documentation intended to be read as `file://` files, so that *other* nefarious suspect files can't do mischief. – Pointy Apr 12 '20 at 13:14
  • [Possible duplicate candidate](https://stackoverflow.com/questions/47417471/creating-cookies-on-file-url-evidence-it-is-being-created-but-not-showing) – Pointy Apr 12 '20 at 13:15

1 Answers1

0

Apparently, I am creating two cookies when using document.cookie correctly. The right way to set the cookie with an expiry date is as below.

$('#gen').on('click', function() {
    var data = "John";
    date = new Date();
    date.setMonth(date.getMonth()+1);
    document.cookie="name="+data+";expires="+date;
});
diggledoot
  • 691
  • 8
  • 22