Javascript [removed] always empty string

前端 未结 5 1050
执念已碎
执念已碎 2020-11-30 01:53

I have this real strange problem with client side javascript setting cookies. I\'m developing a little 1 page demo at the moment to use cookies to store some \'preferences\'

相关标签:
5条回答
  • 2020-11-30 02:07

    This worked for me when ran from localhost, running chrome 28.0.1472.0 canary:

    <!DOCTYPE html>
    <html>
    <head>
      <title>localhost cookie</title>
    </head>
    <body>
      <script type="text/javascript">
        console.log(document.cookie);
        var myCookie = "mycookie=hellocookie";
        document.cookie = myCookie;
      </script>
    </body>
    </html>
    

    Run it in a server, visit the page and look at your cookie store, refresh the page and look at your console.

    It did not set a cookie when opened as a file but worked every time when opened from the server.

    0 讨论(0)
  • 2020-11-30 02:08

    You might have set a wrong path for the cookie.

    In my case I'd set the path in the cookie to /foo because the application is normally on address http://example.org/foo. However, during tests I'd opened the application on the default address http://localhost:3000 which allowed me to create cookies with the path /foo but not read them. The solution was to test the application on address http://localhost:3000/foo.

    0 讨论(0)
  • 2020-11-30 02:09

    HttpOnly cookies cannot be accessed from Javascript and session cookies are usually set as HttpOnly cookies. See also this StackOverflow question: How to read a secure cookie using JavaScript

    So... check whether the cookie you want to read has the 'HttpOnly' flag set... If so, you know the culprit. It's not a bug, it's a feature!

    0 讨论(0)
  • 2020-11-30 02:19

    For usage and docs, see here:

    https://developer.mozilla.org/en-US/docs/DOM/document.cookie

    If you are in Incognito Mode or have cookies disabled, it won't work.

    0 讨论(0)
  • 2020-11-30 02:29

    You can't set cookies by the look of things if its not running in a web server.

    file:///C:/Users/me/Desktop/demo/demo.html

    however:

    http://localhost/demo/demo.html works.

    0 讨论(0)
提交回复
热议问题