简体   繁体   中英

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):

  • visiting 127.0.0.1 - didn't work (port is always 80).
  • Uploading to a web server. Same result as above.
  • visiting the localhost ( localhost and 127.0.0.1 ) on Chrome.

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

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM