You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fix: Correctly handle transition from offline back to online
Previously we were relying on a fetch() succeeding to tell us whether we were back online, but there's no guarantee of a fetch() being attempted (so we stayed "offline" longer than we needed to)
Copy file name to clipboardExpand all lines: public/service-worker.js
+32-5Lines changed: 32 additions & 5 deletions
Original file line number
Diff line number
Diff line change
@@ -77,25 +77,49 @@ function addSecurityHeaders(response) {
77
77
});
78
78
}
79
79
80
-
functionbroadcastOffline(){
80
+
// Tracks whether any network-first request has fallen back to cache, so that we can broadcast ONLINE when the network becomes reachable again
81
+
letservingFromCache=false;
82
+
83
+
self.addEventListener("online",()=>{
84
+
servingFromCache=false;
85
+
broadcast("ONLINE");
86
+
});
87
+
88
+
// Send CHECK_ONLINE when offline. We probe the network directly here because SW-initiated fetches bypass the SW's own fetch handler, hitting the network without being served from cache
Copy file name to clipboardExpand all lines: src/hooks/useIsOnline.js
+12-2Lines changed: 12 additions & 2 deletions
Original file line number
Diff line number
Diff line change
@@ -9,10 +9,10 @@ const useIsOnline = () => {
9
9
window.addEventListener("online",handleOnline);
10
10
window.addEventListener("offline",handleOffline);
11
11
12
-
// The service worker broadcasts OFFLINE whenever a network-first fetch falls back to cache, which reliably catches the case where navigator.onLine hasn't settled yet after a page reload when offline
13
-
// This ensures that we can show "offline" state / UI immediately on page load when offline
12
+
// The service worker broadcasts OFFLINE when a network-first fetch falls back to cache (catching cases where navigator.onLine hasn't settled on page reload), and ONLINE when the network becomes reachable again after a cache fallback period
0 commit comments