/
index.html
47 lines (44 loc) · 1.57 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Protobuf Chat</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<h1>Protobuf Chat</h1>
<section id="chat"></section>
<form>
<input type="text" name="author" placeholder="User name" required />
<input type="text" name="body" placeholder="Message" required />
<button type="submit">Send</button>
</form>
<script>
const $chat = document.querySelector("#chat");
const $form = document.querySelector("form");
const source = new EventSource("/messages");
source.addEventListener("message", (event) => {
// Retrieve the author and body from the event data
const { author, body } = JSON.parse(event.data);
// Append the message to the chat
const $message = document.createElement("article");
const $author = document.createElement("strong");
$author.textContent = author;
$message.append($author, ": ", body);
$chat.append($message);
$chat.scrollTop = $chat.scrollHeight;
});
$form.addEventListener("submit", async (event) => {
event.preventDefault();
const formData = new FormData($form);
await fetch("/post", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(Object.fromEntries(formData)),
});
$form.elements.body.value = "";
});
</script>
</body>
</html>