forked from davidflanagan/jstdg7
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatClient.html
33 lines (31 loc) · 1.47 KB
/
chatClient.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
<html>
<head><title>SSE Chat</title></head>
<body>
<!-- The chat UI is just a single text input field -->
<!-- New chat messages will be inserted before this input field -->
<input id="input" style="width:100%; padding:10px; border:solid black 2px"/>
<script>
// Take care of some UI details
let nick = prompt("Enter your nickname"); // Get user's nickname
let input = document.getElementById("input"); // Find the input field
input.focus(); // Set keyboard focus
// Register for notification of new messages using EventSource
let chat = new EventSource("/chat");
chat.addEventListener("chat", event => { // When a chat message arrives
let div = document.createElement("div"); // Create a <div>
div.append(event.data); // Add text from the message
input.before(div); // And add div before input
input.scrollIntoView(); // Ensure input elt is visible
});
// Post the user's messages to the server using fetch
input.addEventListener("change", ()=>{ // When the user strikes return
fetch("/chat", { // Start an HTTP request to this url.
method: "POST", // Make it a POST request with body
body: nick + ": " + input.value // set to the user's nick and input.
})
.catch(e => console.error); // Ignore response, but log any errors.
input.value = ""; // Clear the input
});
</script>
</body>
</html>