From 112b613075e3befc0d824d7a3019689bb9bbb910 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Rapha=C3=ABl=20Jakse?= Date: Wed, 15 Apr 2020 00:36:09 +0200 Subject: [PATCH] Ensure we close active connections when opening another - second trial --- trivabble.js | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/trivabble.js b/trivabble.js index ff14bd9..caa1562 100644 --- a/trivabble.js +++ b/trivabble.js @@ -884,9 +884,17 @@ } } + function canConnect() { + return !pollingServer && !needsRestart && !connectionStopped && navigator.onLine !== false; + // DO NOT change navigator.onLine !== false by navigator.onLine === true + // This would block connection on a browser not supporting this property + } + function pollServerWithEventSource() { - if (ENABLE_EVENT_SOURCE && window.EventSource) { + if (canConnect() && ENABLE_EVENT_SOURCE && window.EventSource) { closeConnections(); + pollingServer = true; + eventSource = new EventSource("/:trivabble/sse/" + JSON.stringify(cmdsWithContext())); bindConnectionEvents(eventSource); return; @@ -896,8 +904,10 @@ } function pollServerWithWebSocket() { - if (ENABLE_WEBSOCKETS && !blacklistWebsockets && window.WebSocket) { + if (canConnect() && ENABLE_WEBSOCKETS && !blacklistWebsockets && window.WebSocket) { closeConnections(); + pollingServer = true; + webSocket = new WebSocket( (window.location.protocol === "http:" ? "ws://" : "wss://") + window.location.host + @@ -923,6 +933,12 @@ } function pollServerWithXHR() { + if (!canConnect()) { + return; + } + + pollingServer = true; + let currentIndex = 0; let expectedLength = 0; @@ -977,11 +993,6 @@ } function startConnection() { - if (pollingServer || needsRestart || connectionStopped || navigator.onLine === false) { - return; - } - - pollingServer = true; pollServerWithWebSocket(); } -- 2.30.2