Check internet connection javascript

In this article, we are going to teach you how you can check your internet connection using Javascript. We will be displaying a toast or alert message to the user if their internet gets disconnected. And hide the toast when the internet gets reconnected.

Video tutorial:

First, you need to download a library called Toastify. You can download it from GitHub.

After that, you need to include it in your project like this:

<link rel="stylesheet" type="text/css" href="js/toastify.css" />
<script src="js/toastify.js"></script>

Then you need to download another library called Checknet. You can also download it from GitHub too.

You need to include that library as well:

<script src="js/checknet.min.js"></script>

Javascript code to check internet connection

After that, the following code will show a toast message when the internet is down. And it will keep displaying until the network is restored or the toast is manually closed:

<script>

    // create global toastify instance
    var toastify = null;

    // check when the internet is disconnected
    Checknet.addEventListener('dropped', function() {

        // show a toast message
        toastify = Toastify({
            text: "Internet connection lost.",
            duration: -1,
            newWindow: false,
            close: true,
            gravity: "bottom", // `top` or `bottom`
            position: "center", // `left`, `center` or `right`
            stopOnFocus: true, // Prevents dismissing of toast on hover
            style: {
                background: "red",
            },
            onClick: function() {} // Callback after click
        }).showToast();
    });

    // callback when the connection is restored
    Checknet.addEventListener('restored', function() {

        // hide the toast if it is being displayed
        if (toastify != null) {
            toastify.hideToast();
        }
    });

    // start listening for network connectivity
    Checknet.start();

</script>

Refresh the page now and try to disconnect your laptop from the internet. You will immediately see a toast message saying that the internet connection is lost.

Then re-connect the internet, the toast message will be removed automatically. You do not have to refresh the page.

Hope you find this tutorial helpful. If you did, you also browse our Javascript tutorials.