chatthing/static/chat.js

26 lines
1 KiB
JavaScript

init_polling();
// terrible hack. uses polling.
function init_polling() {
let history_el = document.getElementById("history");
let msg_template = document.querySelector("#chatmessage");
setInterval(() => {
let messages = document.getElementsByClassName("message");
let last_msg_uuid = messages[messages.length - 1].id;
fetch(`/poll/${last_msg_uuid}`)
.then(data => data.text().then(bleh => {
let new_messages = JSON.parse(bleh);
for (const message of new_messages) {
const clone = msg_template.content.cloneNode(true);
let msgclone = clone.querySelector("div");
msgclone.id = message.id;
msgclone.classList.add(message.from_admin ? "from_admin" : "from_user");
let content = msgclone.querySelector("p");
content.textContent = message.content;
let ts = msgclone.querySelector(".timestamp");
ts.textContent = message.timestamp;
history_el.appendChild(msgclone);
}
}));
}, 5000)
}