SSE close connection in window.beforeunload #2109
-
👋 hello, I'm in the process of integrating htmx into a traditional SSR site (go templates). I have a number of endpoints When navigating away from these pages, the SSE connection is not closed so if the user navigates to more than 6 pages that start an SSE in quick succession they get a long load time while waiting for one of the abandoned SSE connections to timeout. Is there a way to use the beforeunload window event to close the connection? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I managed to resolve this myself with an addition to I added this function near the helpers. function closeAllSSEConnections() {
document.querySelectorAll('[sse-connect], [hx-sse]').forEach(function(elt) {
var internalData = api.getInternalData(elt);
if (internalData && internalData.sseEventSource) {
internalData.sseEventSource.close();
}
});
} And then attach it to the window on init init: function(apiRef) {
// store a reference to the internal API.
api = apiRef;
// set a function in the public API for creating new EventSource objects
if (htmx.createEventSource == undefined) {
htmx.createEventSource = createEventSource;
}
// (NEW) register the beforeunload event
window.addEventListener('beforeunload', closeAllSSEConnections);
}, This correctly iterates over the SSE connections and closes them when navigating away from the window. IMO this should probably be a default with an argument to disable closing on beforeunload events. Hope this helps anyone else out there! |
Beta Was this translation helpful? Give feedback.
I managed to resolve this myself with an addition to
sse.js
.I added this function near the helpers.
And then attach it to the window on init