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
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 of file://
, 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:
// Save data to localStorage
localStorage.setItem('key', 'value');
// Retrieve data from localStorage
const value = localStorage.getItem('key');
console.log(value); // Outputs: 'value'
// Remove data from localStorage
localStorage.removeItem('key');
// Clear all data from localStorage
localStorage.clear();