From 8657b27f6d66c4eb53c937a7fc3ba01109cd1470 Mon Sep 17 00:00:00 2001 From: Michiel Date: Wed, 4 Sep 2024 10:55:39 +0200 Subject: [PATCH] Automatically reconnect WebSocket Signed-off-by: Michiel --- examples/script.js | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/examples/script.js b/examples/script.js index b3496e5..b722e04 100644 --- a/examples/script.js +++ b/examples/script.js @@ -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(); } };