Read full article in WebMediums

Detect lost internet connection with javascript

How to detect loss of internet connection

Nowadays many websites are loaded by requests javascript so as not to have to load over and over again all the content of a website and only make requests to an API with the necessary data, this sometimes gives headaches when the client loses his connection to the internet and fails the request to the api causing an error depending on the website may be controlled or not.

"Unifi switch" by Thomas Jensen on Unsplash

Let's see a simple way to detect losses of internet connection with javascript and in that case, we can use the data stored in our cache, or a message telling the client that his connection has been lost, so that he can take the appropriate measures.

Detecting the loss of internet connection

Most modern browsers have an event for when the connection is lost, but the old browsers do not so we will use an interval also to have compatibility with all browsers, and also use another method that will make a request to detect this loss since these events sometimes and depending on the browser can send the incorrect data.

Method to detect connection loss compatible with all browsers

function isOnline(path = '/favicon.ico') {
 // Manage IE and more capable browsers
 const xhr = new (window.ActiveXObject || XMLHttpRequest) ('Microsoft.XMLHTTP');

 // Open a new request as HEAD to the root hostname with a random parameter to destroy the cache
xhr.open ('HEAD', `//${window.location.host}${path}?rand=${Math.floor((1 + Math.random ()) * 0x10000)} `, true);

 // Send request and handle response
 return new Promise(resolve => {
 xhr.onreadystatechange = () => {
   if (xhr.readyState === 4) {
     if (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304))
     {
       return resolve(true);
     }
     resolve(false);
   }
 };
 xhr.send(null);
});
}

Recording events and the time interval for older browsers

window.addEventListener('online', async () => { const window.isOnline = await isOnline(); });
window.addEventListener('offline', async () => { const window.isOnline = await isOnline(); });
setInterval(() => {
  window.isOnline = await isOnline();
}, 30000);

We already have everything necessary to detect a connection loss from our client and be able to send an alert message or load the contents directly from the cache in case of having a system prepared to keep these requests in cache, using the storage of the browser for example.

In WebMediums we use something similar to detect these losses in order to show the user the contents directly from the cache and do not have to wait for the connection to fail, trying to give the highest quality reading experience, WebMediums it is accessible without the need to have an internet connection so these methods help us to notify users and show the contents without having to wait for the requests to fail and do not have to wait to consume our articles, of course, if the article that you want to read is not yet in the browser storage we will not be able to show anything.

Detection of lost connection in WebMediums

I hope this information helps you and can implement in your projects.

Written by

Programador web

Articles on free programming and utilities for beginners and professionals, analysis and solutions for complicated situations