Created
September 25, 2022 11:27
-
-
Save percybolmer/d11b64e5477def63c53421ee47d6567b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* login will send a login request to the server and then | |
* connect websocket | |
* */ | |
function login() { | |
let formData = { | |
"username": document.getElementById("username").value, | |
"password": document.getElementById("password").value | |
} | |
// Send the request | |
fetch("login", { | |
method: 'post', | |
body: JSON.stringify(formData), | |
mode: 'cors', | |
}).then((response) => { | |
if (response.ok) { | |
return response.json(); | |
} else { | |
throw 'unauthorized'; | |
} | |
}).then((data) => { | |
// Now we have a OTP, send a Request to Connect to WebSocket | |
connectWebsocket(data.otp); | |
}).catch((e) => { alert(e) }); | |
return false; | |
} | |
/** | |
* ConnectWebsocket will connect to websocket and add listeners | |
* */ | |
function connectWebsocket(otp) { | |
// Check if the browser supports WebSocket | |
if (window["WebSocket"]) { | |
console.log("supports websockets"); | |
// Connect to websocket using OTP as a GET parameter | |
conn = new WebSocket("ws://" + document.location.host + "/ws?otp="+ otp); | |
// Onopen | |
conn.onopen = function (evt) { | |
document.getElementById("connection-header").innerHTML = "Connected to Websocket: true"; | |
} | |
conn.onclose = function(evt) { | |
// Set disconnected | |
document.getElementById("connection-header").innerHTML = "Connected to Websocket: false"; | |
} | |
// Add a listener to the onmessage event | |
conn.onmessage = function (evt) { | |
console.log(evt); | |
// parse websocket message as JSON | |
const eventData = JSON.parse(evt.data); | |
// Assign JSON data to new Event Object | |
const event = Object.assign(new Event, eventData); | |
// Let router manage message | |
routeEvent(event); | |
} | |
} else { | |
alert("Not supporting websockets"); | |
} | |
} | |
/** | |
* Once the website loads | |
* */ | |
window.onload = function () { | |
// Apply our listener functions to the submit event on both forms | |
// we do it this way to avoid redirects | |
document.getElementById("chatroom-selection").onsubmit = changeChatRoom; | |
document.getElementById("chatroom-message").onsubmit = sendMessage; | |
document.getElementById("login-form").onsubmit = login; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment