Introduction to Online Status API

Online and Offline status can be easily figured out by using the online API which is being supported by the navigator object. This particular API returns boolean values telling us whether the browser is online or offline. This is provided by the ability of the browser to provide us updates about the network conditions. This API is very helpful in conditions where you deal with online as well as offline data. For example, consider a website with multiple remote links and there is not Network connectivity. It is possible to retrieve data from the cache in such conditions disabling the links that are not accessible due to the offline status of the browser. Let us see a very simple example of the above and let’s code it out.

Code Based Implementation

A very simple implementation of the Online Status API will be as follows:-

You can see it in action in the repl below

Now one can make use of the event listener in order to enhance the same example. These Event Listeners can be utilized in various ways ranging to the view customization to data sync up as the status of the browser changes.

Adding two event listener makes much of a difference. The two event listener as shown above namely are

  1. Online
  2. Offline

The listeners listen for the events to trigger and then based on them you can change whatever you want to on the DOM or programmatically as well. Let’s see an example of changing certain things on the DOM depending upon these events. Here in this example, we have a simple text which says online/offline depending upon the browsers connectivity.

Just Go Offline and see the above sample in action. One can go Offline and Online multiple times to check this out.

Do remember the implementation of this API is a bit browser specific and browsers have their own definition of when they are offline and online.

This was a small demonstration of the API usage for determining whether the browser is connected or not connected. One can use it to a great extent in order to make their application more accessible.

Join our 2500+ fellow readers

Join our 2500+ fellow readers

Joining our mailing list will for sure keep you at the top of Web Development Ecosystem. Connect with us and also other fellow developers.

You have Successfully Subscribed!

Pin It on Pinterest

Share This