Detect online and offline through JavaScript

How to detect online and offline of a machine through JavaScript? And display a message at the window?

Last updated:7/20/2021 1:53:01 AM

1 Answers

Ethan Karla
Ethan Karla

The Navigator.onLine property returns a Boolean value that specifies whether the browser is in online or offline mode.

Syntax

navigator.onLine

Let's switch to the example for better understanding :

<!DOCTYPE html>

<html>
<head>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <style>
        html{
            scroll-behavior:smooth;
        }
        body {
            margin: 0;
            font-size: 28px;
            font-family: Arial, Helvetica, sans-serif;
        }
    </style>
</head>
<body>
    <div id='online_msg'>
        <div style='position: fixed; bottom: 0; background: #00D100; color: black; width: 100%; text-align: center; z-index: 9999;' id='check_connection'></div>
    </div>
    <script>
        function check_connection() {
            if (navigator.onLine) {
                document.getElementById('check_connection').innerHTML = 'Internet Connected';
                document.getElementById('check_connection').style.backgroundColor = '##00D100';
                document.getElementById('check_connection').style.color = 'black';
            }
            else {
                document.getElementById('check_connection').innerHTML = 'No Internet Connection';
                document.getElementById('check_connection').style.backgroundColor = 'red';
                document.getElementById('check_connection').style.color = 'white';
            }
        }
        setInterval(check_connection, 10);
    </script>
</body>
</html>

Hope this code will be helpful for you.

Happy Coding!

Answer