Skip to content

Commit

Permalink
[REF-3079] state.js: disconnect websocket for window "pagehide" event (
Browse files Browse the repository at this point in the history
…#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
  • Loading branch information
masenf committed Jun 21, 2024
1 parent f41e852 commit 1a74ff4
Showing 1 changed file with 9 additions and 0 deletions.
9 changes: 9 additions & 0 deletions reflex/.templates/web/utils/state.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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.
Expand Down

0 comments on commit 1a74ff4

Please sign in to comment.