I was trying to make a page where we can chat and it will store its user's name to a cookie on the page. I tried it for a couple times, it worked. Then suddenly the cookie part doesn't work anymore. I am hosting the code on replit. What is the problem?
This is my code:
<!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() {
user = prompt("Please enter your name (your name wont be on the internet, use your real name. this is a school chat):","");
if (user != "" && user != null) {
setCookie("name", user, 30);
let user = getCookie("name");
document.getElementById("name").value = user;
}
else {
checkCookie()
}
}
function checkname() {
let user = getCookie("name");
if (user == "" && user == null) {
checkCookie()
}
else{
document.getElementById("welcome").innerHTML = "Welcome Back " + user;
document.getElementById("name").value = user;
}
}
</script>
</head>
<body onload=checkname()></body>
<p id="welcome"></p>
<form action="https://online-chat-2.red78massive157.repl.co" method="post">
Name: <br><input name="name" type="text" id="name" readonly/><br>
Message: <br><input name="message" type="text" style='height:100px; width:1000px' required/><br>
<input value="Send" type="submit"/>
</form>
<button onclick=checkCookie()>Change name</button>
<br><br>
<iframe src="https://online-chat-2.red78massive157.repl.co/chat" style='height:1000px; width:500px'/>
</html>
I am not really sure whats not working for you but I found that checkCookie function has an issue. You are trying to use variable user before initialization.
Rewrite code as
function checkCookie() {
const user = prompt("Please enter your name (your name wont be on the internet, use your real name. this is a school chat):","");
if (user != "" && user != null) {
setCookie("name", user, 30);
document.getElementById("name").value = getCookie("name");
}
else {
checkCookie()
}
}