1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-23 23:51:06 +01:00
actix-extras/actix-ws/examples/chat.html

70 lines
2.2 KiB
HTML
Raw Normal View History

2024-06-20 02:37:37 +02:00
<html>
<head>
<meta charset="utf-8" />
<title>Chat</title>
<script>
function onLoad() {
console.log("BOOTING");
const socket = new WebSocket("ws://localhost:8080/ws");
const input = document.getElementById("chat-input");
const logs = document.getElementById("chat-logs");
if (!input || !logs) {
alert("Couldn't find required elements");
console.err("Couldn't find required elements");
return;
}
input.addEventListener(
"keyup",
(event) => {
if (event.isComposing) {
return;
}
if (event.key != "Enter") {
return;
}
socket.send(input.value);
input.value = "";
},
false
);
socket.onmessage = (event) => {
const newNode = document.createElement("li");
newNode.textContent = event.data;
let firstChild = null;
for (const n of logs.childNodes.values()) {
if (n.nodeType == 1) {
firstChild = n;
break;
}
}
if (firstChild) {
logs.insertBefore(newNode, firstChild);
} else {
logs.appendChild(newNode);
}
};
window.addEventListener("beforeunload", () => {
socket.close();
});
}
if (document.readyState === "complete") {
onLoad();
} else {
document.addEventListener("DOMContentLoaded", onLoad, false);
}
</script>
</head>
<body>
<input id="chat-input" type="test" />
<ul id="chat-logs"></ul>
</body>
</html>