Check if Browser is Online or Offline in JavaScript

← Prev

You can use the navigator .onLine property in JavaScript to find out whether your browser in online or offline. It actually gives you status of your internet connection.

onLine Property Syntax

navigator.onLine

The navigator object provides many useful properties and .onLine is one of them. The navigator.onLine property returns the status of the browser. The property returns a boolean true or false, based on your browser’s status or the internet status (online or offline). The property is read-only.

This is how you can use this property.

<script>
    let status = navigator.onLine;
    alert (status);

    //  or, you can use
    // var status = navigator.onLine;
    // alert (status);
</script>
Try it

The alert message will return true if the browser is online and false if its offline.

Note: You must disable and enable the internet connection to see the result.

Here’s a more realistic example.

The Markup and the Script
<!DOCTYPE html>
<html>
<head>
<style>
    p, div {
        font: 16px Calibri;
    }
    p {
    	text-align: center;
        width: 50px;
        height: 20px;
      	color: #fff;
        border-radius: 10px;
    }
    .online {
    	background-color: #2ed3ae;
    }
    .offline {
    	background-color: red;
    }
</style>
</head>

<body>
    <h4>Enable or disable your internet connection to check the status.</h4>
    
    <div>
        Your current browser status: <p id='status'></p>
    </div>
</body>

<script>
    let update_status = () => {
        const p = document.getElementById('status');
        p.className = navigator.onLine ? 'online' : 'offline';
        p.innerHTML = navigator.onLine ? 'online' : 'offline';
    }

    // or, you can use ...
//     function update_status () {
//         var p = document.getElementById('status');
//         p.className = navigator.onLine ? 'online' : 'offline';
//         p.innerHTML = navigator.onLine ? 'online' : 'offline';
//     }

    window.addEventListener('online',  update_status);
    window.addEventListener('offline',  update_status);
</script>
</html>
Try it

I am using the windows listener event twice to check the actual status of the browser. It will automatically listen to any network changes, whether it has gone offline or online and accordingly updates the <p> element.

Browser Compatibility

IE Edge - Yes it worked
Firefox 62+ - Yes it worked
Chrome (any) - Yes it worked
Opera 56+ - Yes it worked

← Previous


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner