Confessions and Confusions of Ashok M A. Personal and Professional Blog.

Ashok Mannolu Arunachalam, How toJavaScript

How to check and monitor the network status using JavaScript

Have you seen these little toasts messages when you are in a web page showing that you are either offline or online?

That is exactly what we are going to learn in this post to check the network connection using JavaScript.

Check the network connection

Let's first check the network connection first.

if (navigator.onLine) { // yes, it is onLine and not online. ^_^
alert('You are online! 🎉');
} else {
alert('You are offline! 🔌');

The above code just executes one time per load. So, it just notifies the user on entering. This is still good when our app is offline capable.

You can know the status by clicking on the button below too, for tryout!

Try clicking the button after you turned on airplane mode in your device or cutting off the internet.

Monitoring the network status

Let's see how we can monitor the status change using the Web APIs.

() => alert('You are online! 🎉')
() => alert('You are offline! 🔌')

You can monitor the same using the below button.

Once you clicked on the button, we are monitoring the network status. Try again turning on and off the airplane in your device.

Now we can create a status icon for our app or website to notify the user.