Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions static/js/clustermaps/live.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
function initClustermaps() {
// Track whether the page is unloading. Firefox tears down the EventSource
// while navigating away and dispatches an `error` event during unload.
// Without this guard the error handler below calls window.location.reload(),
// which cancels the navigation and snaps the user back to the clustermap
// (and makes external links like CONTRIBUTE appear to "just refresh").
let isUnloading = false;
const markUnloading = function() { isUnloading = true; };
window.addEventListener('pagehide', markUnloading);
window.addEventListener('beforeunload', markUnloading);

// Open a Server Side Events stream for all live locations
const eventSource = new EventSource('/clustermap/locations/live');
// Listen for new locations
Expand All @@ -8,13 +18,22 @@ function initClustermaps() {
updateClustermap(data);
});
eventSource.addEventListener('error', function(event) {
// Don't react while navigating away, and let EventSource handle its own
// automatic reconnection (readyState CONNECTING). Only reload when the
// connection has permanently failed (readyState CLOSED).
if (isUnloading || eventSource.readyState !== EventSource.CLOSED) {
return;
}
console.error('EventSource failed:', event);
window.location.reload();
});
eventSource.addEventListener('open', function(event) {
console.log('EventSource opened');
});
eventSource.addEventListener('close', function(event) {
if (isUnloading) {
return;
}
console.warn('EventSource closed:', event);
window.location.reload();
});
Expand Down
Loading