Better fallback handling when connecting
authorRaphaël Jakse <raphael.trivabble@jakse.fr>
Thu, 8 May 2025 09:09:37 +0000 (11:09 +0200)
committerRaphaël Jakse <raphael.trivabble@jakse.fr>
Thu, 8 May 2025 09:09:37 +0000 (11:09 +0200)
public/trivabble.js

index 04e023a75a9813d892c33aee5240a5e7645b8a0c..b1c57222b11e5caf13637fdf32bdca07d95cba22 100644 (file)
         if (canConnect() && getSetting("ENABLE_EVENT_SOURCE") && window.EventSource) {
             closeConnections();
             pollingServer = true;
-
-            eventSource = new EventSource(getSetting("API_ENTRY_POINT") + "/sse/" + JSON.stringify(cmdsWithContext()));
-            bindConnectionEvents(eventSource);
-            return;
+            try {
+                eventSource = new EventSource(getSetting("API_ENTRY_POINT") + "/sse/" + JSON.stringify(cmdsWithContext()));
+                bindConnectionEvents(eventSource);
+                return;
+            } catch (e) {
+                pollingServer = false;
+                // failed, will fallback to XHR
+            }
         }
 
         pollServerWithXHR();
         if (canConnect() && getSetting("ENABLE_WEBSOCKETS") && !blacklistWebsockets && window.WebSocket) {
             closeConnections();
             pollingServer = true;
-
-            webSocket = new WebSocket(
-                (window.location.protocol === "http:" ? "ws://" : "wss://") +
-                window.location.host +
-                getSetting("API_ENTRY_POINT") + "/ws/" +
-                JSON.stringify(cmdsWithContext())
-            );
-
-            bindConnectionEvents(webSocket);
-            return;
+            try {
+                webSocket = new WebSocket(
+                    (window.location.protocol === "http:" ? "ws://" : "wss://") +
+                    window.location.host +
+                    getSetting("API_ENTRY_POINT") + "/ws/" +
+                    JSON.stringify(cmdsWithContext())
+                );
+                bindConnectionEvents(webSocket);
+                return;
+            } catch (e) {
+                // failed, will fall back to event source
+                pollingServer = false;
+            }
         }
 
         pollServerWithEventSource();