How to check for active internet connection in JavaScript?

I’m working on a project that needs to check if the internet is working. The usual navigator.onLine method doesn’t seem to do the trick. It only tells me if the browser thinks it’s online, not if there’s actually an internet connection.

Here’s what I tried:

function checkConnection() {
  if (window.networkStatus === 'connected') {
    console.log('Internet is working!');
  } else {
    console.log('No internet connection.');
  }
}

document.addEventListener('DOMContentLoaded', checkConnection);

This doesn’t work as expected. I need a reliable way to check if the internet is really connected, not just what the browser thinks. It’s for a contact form in my app that needs to warn users if they can’t send their message.

Any ideas on how to do this properly? Thanks!

hey mate, have u tried using the online/offline events? they’re pretty handy. something like:

window.addEventListener(‘online’, () => console.log(‘back online!’));
window.addEventListener(‘offline’, () => console.log(‘oops, no internet’));

it’s simple but works well for most cases. just remember to add error handling for ur form submits too!

I’ve dealt with this issue before, and it can be tricky. The most reliable method I’ve found is to actually ping a known server. Here’s what worked for me:

function checkInternetConnection() {
  return fetch('https://www.google.com', { mode: 'no-cors' })
    .then(() => true)
    .catch(() => false);
}

// Usage
checkInternetConnection().then(isOnline => {
  if (isOnline) {
    console.log('Internet is connected');
    // Enable your contact form
  } else {
    console.log('No internet connection');
    // Show warning to user
  }
});

This approach attempts to fetch Google’s homepage. If successful, you know there’s an active connection. If it fails, you can assume the internet is down. Just remember, this is an asynchronous operation, so you’ll need to handle it with promises or async/await.

Keep in mind that this method isn’t foolproof (nothing really is), but it’s more reliable than navigator.onLine in my experience. Hope this helps with your contact form!

Another approach you might consider is using the Navigator.connection API. It provides more detailed information about the network connection. Here’s a simple implementation:

function checkConnection() {
  const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
  
  if (connection && connection.type !== 'none') {
    console.log('Internet seems to be working');
    return true;
  } else {
    console.log('No internet connection detected');
    return false;
  }
}

This method checks the connection type and assumes there’s no internet if it’s ‘none’. It’s not 100% foolproof, but it’s lightweight and doesn’t require external requests. You could combine this with an actual fetch request for critical operations to ensure reliability.