I’m trying to get my head around cookies. I have read several web sites for help and came up eventually with this:
<!doctype html>
<html>
<head>
<title>Cookie test</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script>
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+";"+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var 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() {
var user=getCookie("username");
if (user != "") {
alert("Hello again " + user);
} else {
user = prompt("Please tell me your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
</script>
</head>
<body onload="checkCookie()">
<p>This is a cookie test</p>
</body>
</html>
When I call this html file I get the prompt for my name. Then I close the page, reopen it and get another request for my name. What I expected was the “Hello again” message.
What am I doing wrong?
I’ve looked at the material you suggested, but I still can’t get mine to work.
Can you please tell me what is wrong with my code as originally posted?
Thanks, Ken
(Sorry for the delay in replying. We veterans never have enough time for all our trivia!)
All the browsers I use (mainly Opera and MS Edge on a Windows 10 laptop) work normally with other sites’ cookies (i.e. they remember them), but not the stuff I’ve tried. Do I have to get my service provider to tweak my account? In any case, what’s wrong with my original code? (It is just a little test file, so is incomplete,)
script in the head instead of at the bottom of the body
use of debugging alert and prompt calls to display messages instead of console.log
JavaScript jumbled with HTML instead of in separate file
probably a lot more but those are the most obvious