How to check if internet is connected with browser using JS?

Asked 19-Jul-2021
Viewed 575 times

1 Answer


2

<!DOCTYPE html>

<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
    <p id='status'></p>
    <script>
        var i = 0;
        setInterval(checkConnection, 1000);
        function checkConnection() {
            if (window.navigator.onLine) {
                document.getElementById('status').innerHTML = 'Connected !!!';
                window.document.body.style.backgroundColor = 'green';
            }
            else {
                document.getElementById('status').innerHTML = 'Disconnected !!!';
                window.document.body.style.backgroundColor = 'red';
            }
        }
    </script>
</body>
</html>