Ensure we close active connections when opening another - second trial
authorRaphaël Jakse <raphael.trivabble@jakse.fr>
Tue, 14 Apr 2020 22:36:09 +0000 (00:36 +0200)
committerRaphaël Jakse <raphael.trivabble@jakse.fr>
Tue, 14 Apr 2020 22:36:09 +0000 (00:36 +0200)
trivabble.js

index ff14bd9ad57b8a57159811a974d3149f459458f1..caa15626dc78d08dbc83aba910f41d6428aaf650 100644 (file)
         }
     }
 
+    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;
     }
 
     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 +
     }
 
     function pollServerWithXHR() {
+        if (!canConnect()) {
+            return;
+        }
+
+        pollingServer = true;
+
         let currentIndex = 0;
         let expectedLength = 0;
 
     }
 
     function startConnection() {
-        if (pollingServer || needsRestart || connectionStopped || navigator.onLine === false) {
-            return;
-        }
-
-        pollingServer = true;
         pollServerWithWebSocket();
     }