randomdude
randomdude

Reputation: 383

Cannot set cookie path to the root directory with Javascript

On localhost. Using Firefox 88.0 (Private window). My document tree:

/index.html
/page1/index.php
/page2/index.php

Here's my JS to set cookies (on page1):

function setCookie(name, value) {
  document.cookie = name + "=" + value;
  document.cookie = "path=/";
}

Which (I think) overwrites the cookie path to / every time I call the function. At the beginning of the same JS file I have: alert(document.cookie);. It displays the full cookie as I save it, including path=/.

On the homepage (/index.html) I have: <script>alert(document.cookie);</script>. But it displays an empty alert. I don't see the cookies. But if I go back to the page1 then I see the cookies again. Why is this?

I've also tried (solutions from other SO answers):

Couldn't resolve. Could anyone help please? Thank you in advance!

Upvotes: 0

Views: 3814

Answers (1)

randomdude
randomdude

Reputation: 383

Apparently I have to set the path at the time of setting the cookie, not using document.cookie after the cookie has already been set.

This got the problem fixed:

function setCookie(name, value) {
  document.cookie = name + "=" + value + ";path=/"; //Set the path while setting the Value.
}

Upvotes: 3

Related Questions