DEV Community

Cover image for Hey bro, you online?

Posted on

Hey bro, you online?

Sometimes the user might a have a bad internet connection which may cause your site to not function properly. So it sounds like a good idea to let your user know when the internet goes off.
And guess what? It is really easy to do using navigator.connection. Here is a basic example.

navigator.connection.onchange = function(){
        alert("Your internet connection is back");
        alert("Your currently offline");
Enter fullscreen mode Exit fullscreen mode

Discussion (4)

lukeshiru profile image
Luke Shiru

The issue with this approach is that you're basically always sending alerts, even if there was a change on the connection but the user is still online, so ideally you should have some kind of track of the previous state:

let { onLine } = navigator;

navigator.connection.addEventListener("change", () =>
    onLine !== navigator.onLine
        ? (alert(
                    ? "Your internet connection is back"
                    : "Your currently offline"
          (onLine = navigator.onLine))
        : undefined
Enter fullscreen mode Exit fullscreen mode


thomasbnt profile image
Thomas Bnt

Clear πŸ‘€

aboss123 profile image
Ashish Bailkeri

This is pretty cool!

0shuvo0 profile image
Shuvo Author

Glad you liked it