I am using service worker to check if a user is online or offline when a request is made. Here are some of the approaches I have taken:
- In this method in service worker,
self.addEventListener("fetch", (event) => {
if (navigator.onLine){
}
})
navigator.onLine
only works when you check/uncheck the offline checkbox in Inspect Element. But when I switch the device's internet on/off, it will always return true whether im offline or online.
And also from what i've seen in other answers, navigator.onLine
will return true if you are connected to your local network even if your local network has no internet connection.
I have tried to ping a url in the
self.addEventListener("fetch", {...})
method as shown here https://stackoverflow.com/a/24378589/6756827. This will bring an error in in thenew XMLHttpRequest();
object.I have tried to load an online resource (an image) in the
self.addEventListener("fetch", {...})
method as shown here https://stackoverflow.com/a/29823818/6756827. The console shows an error fornew Image();
.
Because none of these approaches work, how do we check if a user is online or offline in service worker when a request is made ?