Browse Source

[REF-3079] state.js: disconnect websocket for window "pagehide" event (#3540)

All major browser use a "bfcache" to freeze pages when navigating away from the
domain, then they restore the page when going back.

However if the page uses websockets, these get kind of stuck unless you
disconnect them before freezing (and have a mechanism for reconnecting, which
we already do).

Ref: https://web.dev/articles/bfcache

Fix #3478
Masen Furer 11 months ago
parent
commit
1a74ff4d45
1 changed files with 9 additions and 0 deletions
  1. 9 0
      reflex/.templates/web/utils/state.js

+ 9 - 0
reflex/.templates/web/utils/state.js

@@ -388,9 +388,17 @@ export const connect = async (
     }
   }
 
+  const pagehideHandler = (event) => {
+    if (event.persisted && socket.current?.connected) {
+      console.log("Disconnect backend before bfcache on navigation");
+      socket.current.disconnect();
+    }
+  }
+
   // Once the socket is open, hydrate the page.
   socket.current.on("connect", () => {
     setConnectErrors([]);
+    window.addEventListener("pagehide", pagehideHandler);
   });
 
   socket.current.on("connect_error", (error) => {
@@ -400,6 +408,7 @@ export const connect = async (
   // When the socket disconnects reset the event_processing flag
   socket.current.on("disconnect", () => {
     event_processing = false;
+    window.removeEventListener("pagehide", pagehideHandler);
   });
 
   // On each received message, queue the updates and events.