Online connectivity check using plain javascript

Internet connection is not always consistent and hence it’s mandatory for an application to check internet connectivity, before performing few actions to ensure no data is lost.

If we use frontend frameworks like react, angular, vue or ionic, there are a lot of packages in the market check the online/offline status. I am developing a sample application where I use only plain html and javascript. In this case, we need to use native event emitters of the browser. I am using Chrome Version 86.0.4240.111 (Official Build) (64-bit). I have refered various places in stackoverflow and many other blogs, but nothing worked for me. Then I found something that works. Am sharing it here.

This code will not work when you turnoff your wifi.

  1. Open google developer tools Console (Ctrl+Shift+I).
  2. Click Toggle device bar or do Click Ctrl+Shift+M. You can see the mobile view here.
  3. At the top of this view, we will have option to select device, adjust size and then there is a drop down where you can switch between online and offline. Check the below screenshots.
Offline- Console message is “The network connection has been lost”
Online- console message is “The network connection is back”

This method is mostly helpful during development. For production applications, obviously we will use any framework where we can use libraries to check connectivity more efficiently.

--

--