mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-26 10:27:42 +02:00
docs: split chat example
This commit is contained in:
69
actix-ws/examples/chat.html
Normal file
69
actix-ws/examples/chat.html
Normal file
@ -0,0 +1,69 @@
|
||||
<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>
|
Reference in New Issue
Block a user