1

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:

  1. 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.

  1. 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 the new XMLHttpRequest(); object.

  2. 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 for new 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 ?

Ian Munge
  • 27
  • 7
  • As a general rule, the only way to know at some given moment if an internet connection has been made is to attempt to make contact to some other host and get a response. That's pretty much how the Internet works. – Pointy Aug 18 '20 at 16:00

1 Answers1

0

In the service worker you do not have access to the navigator object and thus no access to the online property or events.

Instead you know you are offline when a fetch throws an exception. The only time a fetch will throw an exception is when the device cannot connect to the Internet/Network.

self.addEventListener( "fetch", function ( event ) {

event.respondWith(

    handleRequest( event )
    .catch( err => {
        //assume offline as everything else should be handled
        return caches.match( doc_fallback, {
            ignoreSearch: true
        } );

    } )

);

} );

For a more complex handling of the situation you can sync messages of online/offline state with the UI using the message API:

self.addEventListener( "message", event => {
    //handle message here
}
Chris Love
  • 3,740
  • 1
  • 19
  • 16