0

I am using the setCookie() and getCookie() functions posted in an answer to this question

Cannot set cookies in Javascript

When I set the cookie and reload the page, the cookie is there and working properly. But when I open a new tab (or close my current tab and reopen it) the cookie disappears. Is this because I'm developing locally or for some other reason?

Evan Hessler
  • 297
  • 3
  • 19
  • 1
    @eykjs um, you can set cookies in JavaScript, not sure what you are talking about. – epascarello Nov 03 '17 at 19:33
  • 1
    You should be setting an expiration date – epascarello Nov 03 '17 at 19:34
  • https://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie – epascarello Nov 03 '17 at 19:35
  • Yea sorry that's just the title of the post I'm linking to, I know you can set cookies in Javascript. My problem is even with an expiration date I'm not getting the value back in a new tab. I'm using Chrome if that matters. – Evan Hessler Nov 03 '17 at 20:11
  • Were you able to solve this?I am having the same issue. When I open a new tab the cookie insnt there unless i reload the new tab. Due to this, i get an error page when opening the tab for the first time – Chilarai Jul 09 '20 at 05:39
  • I'm trying to jog my memory but I can't even remember which project I was working on for this. I'll keep digging through my repos to see if I can find a solution. – Evan Hessler Jul 10 '20 at 21:42
  • Might've been a CORS issue. See: https://stackoverflow.com/questions/59808537/cookies-headers-are-present-but-cookies-are-not-stored-in-browser – Evan Hessler Jul 10 '20 at 21:44

1 Answers1

0

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

With JavaScript, a cookie can be created like this:

document.cookie = "username=John Doe";

You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed:

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";

With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.

document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";

source: https://www.w3schools.com/js/js_cookies.asp

Subhrajyoti Das
  • 2,685
  • 3
  • 21
  • 36
  • So I thought it had to do with my expiry date not being set but I'm still getting the same result... Here's my code for clarification: `function setCookie(cname, cvalue, exdays) { // same code as the setCookie method in the w3Schools link you sent } setCookie('accessToken', token, 1); ` Can I not set a cookie when using localhost? – Evan Hessler Nov 03 '17 at 19:58