var chatlog = []; function sendMessage() { let id = window.location.href.split("/").slice(-1)[0] message = document.getElementById("chatbox-input-box").value document.getElementById("chatbox-input-box").value = '' document.getElementById("chatbox-input-box").disabled = true; chatlog.push(["user", message]) renderChatlog(); var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) { message = this.responseText.replace("\n", "
"); } else { message = "Encountered an error while trying to get a response."; } chatlog.push(["bot", message]); renderChatlog(); document.getElementById("chatbox-input-box").disabled = false; } }; xhttp.open("GET", `/bot/chat/${id}/message`, true); xhttp.send(); return false; } function renderChatlog() { let chatbox = document.getElementById("chatbox"); let out = ""; if (chatlog.length > 50) { chatlog.shift(); //only keep the 50 most recent messages to avoid slowdown } chatlog.forEach(function(item, i) { if (item[0] == "user") { out += `
${item[1]}
`; } else { out += `
${item[1]}
`; } }) chatbox.innerHTML = out; chatbox.scrollTop = chatbox.scrollHeight; }