Skip to content

Commit

Permalink
Automatically reconnect WebSocket
Browse files Browse the repository at this point in the history
Signed-off-by: Michiel <[email protected]>
  • Loading branch information
michielp1807 authored and tweedegolf-marc committed Sep 4, 2024
1 parent f6d1d4a commit 576b6a8
Showing 1 changed file with 16 additions and 13 deletions.
29 changes: 16 additions & 13 deletions examples/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -106,20 +106,23 @@ const updateIdentities = async () => {

// listen for messages on websocket
if (!ws) {
const proto = window.location.protocol === 'http:' ? 'ws' : 'wss';
ws = new WebSocket(`${proto}://${window.location.host}/receive-messages`);
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
const messagesContainer =
document.querySelector('.received-messages');
messagesContainer.appendChild(renderMessage(message));
});
ws.addEventListener('open', () => {
Object.values(identities).forEach((identity) => {
ws.send(JSON.stringify(identity));
registered.push(identity.id);
function connectWS() {
const proto = window.location.protocol === 'http:' ? 'ws' : 'wss';
ws = new WebSocket(`${proto}://${window.location.host}/receive-messages`);
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
const messagesContainer = document.querySelector('.received-messages');
messagesContainer.appendChild(renderMessage(message));
});
});
ws.addEventListener('open', () => {
Object.values(identities).forEach((identity) => {
ws.send(JSON.stringify(identity));
registered.push(identity.id);
});
});
ws.addEventListener('close', connectWS);
}
connectWS();
}
};

Expand Down

0 comments on commit 576b6a8

Please sign in to comment.