Detect network online/offline State using JavaScript

June 20, 2020

Detect Current online state

We can detect if the user is online or offline by using the onLine property on the navigator object which will return true if the user is connected to the internet, otherwise it returns false.

navigator.onLine; //true if has internet otherwise false

Detect internet connection state change

online and offline events will be triggered if the user's internet connections state changes. So we can add an online and offline event listener to the window and perform respective actions based on the online and offline state.

function updateStatus(){
        console.log("Your connected");
    } else {
        console.log("Connection lost");
window.addEventListener("online", updateStatus);
window.addEventListener("offline", updateStatus);

Please donate here, for making more tutorials.