2021年1月17日星期日

Client-side cookies turning up as blank string in simple HTML/vanilla JS page

I am trying to get some practice working with cookies. I am trying to practice this by creating a very simple page where the user chooses either light or dark mode. When they click the button, I save their selection within a cookie (I know that localStorage would also work, but I want to play around with cookies).

I've done some searching on stack overflow and most people's questions are for more complex situations with cookies involving server-side issues. Though some answers have mentioned problems with cookies being saved on localhost. I'm simply opening my html page in my browser: file:///Users/wl/projects/cookies/index.html. Will cookies not be set on a local file such as this one?

Is there a way for me to practice working with cookies on the client-side locally?

index.html

<!DOCTYPE html>    <html lang="en">    <head>      <meta charset="utf-8" />      <link rel="stylesheet" href="style.css" />            <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">    </head>      <body class="container">      <script src="main.js"></script>      <div class="selectTheme">        <h1>Pick a theme:</h1>        <button type="button" id="lightMode" class="btn btn-light">Light Mode</button>        <button type="button" id="darkMode" class="btn btn-danger dark">Dark Mode</button>      </div>      </body>  </html>  

main.js (all of the console.logs come up blank, but I think they should return the cookie string that I just set)

  document.addEventListener("DOMContentLoaded", ()=>{    document.querySelector("#lightMode").addEventListener("click", ()=>{      document.cookie="theme=light; maxAge=500000000"      console.log(document.cookie)    })    document.querySelector("#darkMode").addEventListener("click", ()=>{      document.cookie="theme=dark; maxAge=500000000"      console.log(document.cookie)    })      })    console.log(document.cookie)    
https://stackoverflow.com/questions/65768309/client-side-cookies-turning-up-as-blank-string-in-simple-html-vanilla-js-page January 18, 2021 at 11:06AM

没有评论:

发表评论