How to Detect internet connection JavaScript

In this tutorial, We will see how to detect internet connection using javascript. This is a pretty simple code to check the internet connection active or not.

Why we use this method: Most of the website uses this method to improve better user experience, If you check for the big website like Netflix, Quora and Google, they are using the same method to show the warning message of No internet connection.

  • For the better user experience
  • Let user stay on your site
  • Increase user communication with your page


Detect internet connection JavaScript

Syntax to check internet connection is active or not using javascript

Here I am sharing the 3 Syntax by which we can identify the internet connection active or not.

Click here For the DEMO

<button onclick="fn_checkInternet()">

        Click Here to Check

    </button>

    // Javascript Code

    <script>

        function fn_checkInternet()

        {

            if (navigator.onLine)

            {

                alert('Online');

            }

            else

            {

                alert('Offline');

            }

        }

 

        window.addEventListener('online', function (e)

        {

            alert('You Are Back Online');

        }, false);

 

        window.addEventListener('offline', function (e)

        {

            alert('You went offline');

        }, false);

    </script>


Explanation of Syntax

1. To check if the user is online or offline during any activity on-page done by the user call the fn_checkInternet() function.

function fn_checkInternet()

        {

            if (navigator.onLine)

            {

                alert('Online');

            }

            else

            {

                alert('Offline');

            }

        }

2. Check if suddenly the user's connection is down.


 window.addEventListener('offline'function (e)

        {

            alert('You went offline');

        }, false);


3. Check if  user back online or internet started working.


 window.addEventListener('online'function (e)

        {

            alert('You Are Back Online');

        }, false);

Post a Comment

Post a Comment (0)

Previous Post Next Post