Detect If Internet Connection Exists with JavaScript

There are times when the user might be browsing and loose the internet connectivity all of a sudden or user might be doing an offline browsing which comes basically from HTML 5 and the mobile apps keep the content offline for the user to read later even without internet connection. It will be very helpful if we know the user is online having an active internet connection, and the best way to Detect If Internet Connection Exists with JavaScript is by navigator property.

navigator.onLine

The navigator.onLine property provides the Boolean result (true/false) for whether or not the user is connected to the internet. Note this property works properly in all the modern browsers seamlessly, doing so in old browsers may not yield the exact result sometimes.

Syntax to use navigator.onLine

Hook into Events
In addition to checking the navigator property if you need to perform some operations using online and offline it is easy to hook into events.

Detect If Internet Connection Exists with JavaScript Using XHR request

The navigator.onLine API is not much reliable and might face issues sometimes and it works efficiently with the modern browser.Alternatively, to Detect If Internet Connection Exists with JavaScript is by using XHR request to your own server or to a google server as the up-time of google would be higher.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.