Is there a way to detect if a user has connected back to network/online using a service worker?
I would like to fetch some data when user comes back to network.
It could probably be done in fetch event handler, but I would prefer less hacky solution.
Pseudo code of hacky solution I came up:
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request)
.then(function(res) {
// check previous status
// if previous status == offline, user is back online
// do back online stuff...
// set status to online if previous status is offline
})
.catch(function(err) {
// set status to offline
})
);
});
You cannot detect the moment (event) of getting back to online state from an offline state in the Service Worker itself. However, if you're interested specifically about that, you can utilize the online
and offline
events in the window
object. In other words, you could add event listeners in your regular JavaScript code running on the page (NOT in the SW) for these events and whenever they occur, notify the SW through the postMessage API
. This way your JS on the page detects the online/offline changes and notifies the SW, after which the SW may use that information for whatever purpose it wants.
One thing to notice: these online/offline events don't fire if the browser is closed or if the user is not viewing the page, because they happen in the page's JS execution context. This is by design: you shouldn't be able to create a Service Worker that continuously tracks the user's connectivity state.
As others have pointed, depending on what you're really interested in ("when does the connectivity change happen" vs. "how to check if online/offline in SW") this might be a duplicate question and I suggest you read the linked answer.
From what you're asking I imagine you would like to do some sort of syncing between the client and the server, wouldn't you? If that's so, I suggest you read about the Background Sync API
which is supported at least by Chrome, it might help you. Here's some examples of use with the Workbox library https://developers.google.com/web/tools/workbox/modules/workbox-background-sync