-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (53 loc) · 1.92 KB
/
index.js
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
48
49
50
51
52
53
54
55
56
57
58
59
60
const host = `ws://${ location.hostname }:57772`;
const myName = "Nikita";
const myAvatar = "http://nikita.tk/img/avatar.jpg";
let URL = host + "/csp/user/WebCourse.ChatWebSocket.cls",
ws = new WebSocket(URL);
ws.addEventListener("open", () => ws.send(JSON.stringify({
name: myName,
avatar: myAvatar
})));
ws.addEventListener("error", (err) => printMessage({
name: "System",
text: "Connection error: " + err.toString()
}));
ws.addEventListener("close", () => printMessage({
name: "System",
text: "We're out!"
}));
ws.addEventListener("message", (m) => {
let message = JSON.parse(m.data);
if (message["error"])
return console.error(`Server reporting an error: ${ message.error }`);
if (message["updates"] instanceof Array) message["updates"].forEach(update => {
if (update.type === "message")
printMessage(update);
else if (update.type === "notification")
printMessage(update);
else
console.warn("Unhandled WebSocket message", message);
});
});
function printMessage ({ date = Date.now(), name, text, avatar = "" }) {
let block = document.querySelector(".messages");
block.innerHTML += `<div class="message">
<div class="avatar" style="background-image: url(${ avatar })"></div>
<div class="body">
<div class="headline">
<span class="date">${ new Date(date).toLocaleString() }</span>,
<span class="name">${ name }</span>
</div>
<div class="text">${ text }</div>
</div>
</div>`;
document.body.scrollTop = 99999999;
}
document.addEventListener("DOMContentLoaded", () => {
const input = document.querySelector(".input");
input.addEventListener("keydown", (event) => {
if (input.value && event.keyCode === 13) {
ws.send(JSON.stringify({ "text": input.value }));
input.value = "";
}
});
});