Knowing if a user has no internet connection


#1

Is there a way, particularly in Electron, to detect whether a device can actively connect to the internet, or better yet can connect reliably?

The documentation recommends using navigator.onLine, however the way Chrom(e/ium) implements this, it only checks that the machine is connected to some form of LAN. This means that given false, the user is definitely offline, but doesn’t guarantee that there is an internet connection on true. This becomes apparent when turning on throttling in DevTools ( I have it set to “Offline”) which is certainly a lot easier than pulling the cable out of my machine every time I want to check offline behaviour.

I can work around this, but if there’s something baked in, that can do it more reliably, that would be ace.


#2

In my experience, the only way to truly know that a machine is on the world-wide Internet is to attempt to connect to a machine that is on the world-wide Internet. Lots of corporate and government networks are Internet-like networks with their own web, mail and DNS servers. You could be in a system like that and it would look for all intents and purposes just like the Internet … except you couldn’t get to the server you wanted.


#3

That was my worry. It’s something I can work with.

My main issue was that I’ve got a piece of code that only fires when online, checking to see if MP3s are blocked. Since we target schools, there are often blocks in place which give a variety of different responses. A 404 code mean a block, but so could a 200, or basically whatever status code the block manufacturer fancies. I’ll just have to do a request beforehand to check for the connection.

I’ll mull it over, I do subscribe to a channel of server sent events using EventSource, that’s probably a good place to start.

Cheers


#4

You might find is-online useful.


#5

It sounds pretty cool, and it’s likely something I’d use in a project of my own, but it’s not something I’d feel comfortable using in production.

I think I’ve got it sorted, we use EventSource to transmit messages from the website to the Electron app for when they’re being used simultaneously (it doesn’t make so much sense in this scenario, but it’s also a Cordova app for tablets). I can listen for errors in connecting to the event stream to see if I’m offline, and poll for a reconnect when I’m offline to determine when I’m back online.


#6

There’s a web API for that:

  console.log('at any moment you can check with navigator.onLine', navigator.onLine)
  
  const updateOnLineStatus = () => {
    // whatever
  }

  window.addEventListener('online', updateOnLineStatus)
  window.addEventListener('offline', updateOnLineStatus)

#7

Like I said in the first post, this doesn’t give actual online/offline information, particularly if connected to a network with no internet, it shows only whether there’s a connection.