Check if Internet Connection Exists using Javascript

Last Reply on May 05, 2016 07:19 AM By power

Posted on May 03, 2016 02:05 AM

Hi, I was searching for a solution when internet is not connected or when a week signal is detected and I got the code below from your website. Then I added alert message as you can see below to prevent website from crashing. When I try to use it in my login page, it flickers the page every 4 seconds(the time i set) and the cursor goes back to the Username textbox before I finish entering the password. I set txtUsername.focus on pageload. How do I prevent the page from flickering until I finish entering the username and password.

<script type="text/javascript">
        window.onload = function () {
            setInterval(function () {
                if (navigator.onLine) {
                    document.forms[0].submit();
                }
                else
                    alert("You are not connected to Internet, ensure you’re not in airplane mode. \n\nYour internet signal may be week. \n\nPlease connect to internet and try again.");
            }, 4000);
        }
    </script>

 

Posted on May 03, 2016 02:05 AM Modified on on May 05, 2016 09:22 AM
power says:
<script type="text/javascript">
        window.onload = function () {
            setInterval(function () {
                if (navigator.onLine) {
                    document.forms[0].submit();
                }
                else
                    alert("You are not connected to Internet, ensure you’re not in airplane mode. \n\nYour internet signal may be week. \n\nPlease connect to internet and try again.");
            }, 4000);
        }
    </script>

 Hi,

Replace above code with

<script type="text/javascript">
    window.onload = function () {
        if (!navigator.onLine) {
            alert("You are not connected to Internet, ensure you’re not in airplane mode. \n\nYour internet signal may be week. \n\nPlease connect to internet and try again.");
        }
    }
</script>

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function () {
            if (!navigator.onLine) {
                alert("You are not connected to Internet, ensure you’re not in airplane mode. \n\nYour internet signal may be week. \n\nPlease connect to internet and try again.");
            } else {
                alert("You are connected to Internet");
            }
        }
    </script>
</head>
<body>
</body>
</html>

Demo

I hope this will help you out.