Check Internet Connectivity – Javascript

0
(0)

In this article, we are going to show you how you can show a toast/alert message to the user if their internet gets disconnected.

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>

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.

How useful was this post

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post





Please disable your adblocker or whitelist this site!