-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.js
30 lines (25 loc) · 1.14 KB
/
websocket.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
// small helper function for selecting element by id
let id = id => document.getElementById(id);
//Establish the WebSocket connection and set up event handlers
//let ws = new WebSocket("ws://" + location.hostname + ":" + location.port + "/chat");
let ws = new WebSocket("wss://u6k9ujsvz7.execute-api.us-east-1.amazonaws.com/dev");
ws.onopen = () => alert("WebSocket opened");
ws.onclose = () => alert("WebSocket connection closed");
ws.onmessage = msg => updateChat(msg);
// Add event listeners to button and input field
id("send").addEventListener("click", () => sendAndClear(id("message").value));
id("message").addEventListener("keypress", function (e) {
if (e.keyCode === 13) { // Send message if enter is pressed in input field
sendAndClear(e.target.value);
}
});
function sendAndClear(message) {
if (message !== "") {
ws.send(JSON.stringify({'route': 'sendMessage', 'data': message}));
id("message").value = "";
}
}
function updateChat(messageEvent) { // Update chat-panel and list of connected users
console.log(messageEvent)
id("chat").textContent = messageEvent.data; // replace any old chat data with new
}