Sometimes your internet is not connected and you are trying to save some important information, suddenly data is lost because of the internet. 


You can notify users that you are offline or when your internet is back then display online. This will help your users to know that their internet is having some trouble and they can not get any updates or save information on your websites.


Detecting connection status


We can leverage the navigator.onLine API to detect the connection status. This will return a boolean to indicate whether the user is online.


This would work great on the initial load so we could do something like this.


window.addEventListener('load', () => {

  const status = navigator.onLine;

});


But we won't know if the network status changes after load, which is not ideal.


We can subscribe to offline and online events to listen to those specific changes.


window.addEventListener('offline', (e) => {

  console.log('offline');

});


window.addEventListener('online', (e) => {

  console.log('online');

});


You can use the above in one single program and implement it on your website based on your requirement.


Example:


window.addEventListener('load', () => {

  const status = navigator.onLine;

  if(status)

  {

    console.log('online');

  }

  else

  {

   console.log('offline'); 

  }

});


window.addEventListener('offline', (e) => {

  console.log('offline');

  });


window.addEventListener('online', (e) => {

  console.log('online');

});


I hope this program to detect whether the user is online or offline will help your application. If you have any doubts, let us know in the comments.