I try this sample to read and save cookies and work fine in my Chrome browser. Ask my name and after refresh doesn’t ask it again
https://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username
Now I save the code to one HTML file and doesn’t have the same effect. After each refresh, ask my name again. So doesn’t seem to be saving the cookie.
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for(let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
let user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()"></body>
</html>
Try in Edge browser and same result on both test.
This is my attempt to simplify the code to find the problem on my original code where the cookie isn’t being saved either.
Even when debugging in console the SaveCookie function is called but the GetCookie doesn’t get anything.
In console, I can do document.cookie and try to create a cookie but doesnt seem to work either
2
Answers
Many browsers have restrictions on setting cookies for local files (those accessed via the file:// protocol) due to security reasons.
You can use a Local Server: This way, your files are served over
http://
instead offile://
, and cookies will work as expected. You can use simple tools like Python's built-in HTTP server or Node.js.But for me that isnt an option, so I will use localStorage or sessionStorage as an alternative to cookies. These storage mechanisms are supported for local files.
Here's a simple example of how to use localStorage:
Use a (development) server
See this question:
(emphasis original)
Your code also does not work for me if I just launch it in Google Chrome.
However, it works perfectly for me when I host it with Five Server (any other development server would suffice), so the problem is that you view your page via the
file:///
protocol, nothttp://
orhttps://
.Cookies will work if you deploy your page on a remote server as well, of course.