I’m working on an HTML application that runs through XULRunner and need to verify if the user has an active internet connection. I tried using the navigator.onLine property but it’s not working as expected.
$(document).ready(function() {
function checkConnection() {
var isConnected = navigator.onLine;
if (isConnected) {
alert("Connected to internet!");
} else {
alert("No internet connection!");
}
}
checkConnection();
});
The problem is that this method only checks if the browser thinks it’s online, not if there’s actually a working internet connection. My app has a contact form that needs to warn users when they’re offline before they try to submit it. What’s the most reliable way to test for real internet connectivity in JavaScript?
The fetch API with a timeout works great for this. I hit the same issue building a web app that needed solid connectivity detection. What worked for me was hitting a small resource on my own server or a public API, then catching network errors or timeouts. Use fetch with AbortController to handle timeouts properly. The trick is picking an endpoint that’s fast and reliable. I usually go with a simple JSON endpoint that returns something tiny - 1KB or less. This gives you real network reachability instead of just what the browser thinks is online. You can add exponential backoff if you want to retry failed requests before calling the connection dead.
Just make a lightweight HTTP request to a reliable endpoint and check if it responds. I use HEAD requests to Google’s public DNS or a CDN since they’re rock solid. Set a 5-second timeout so it doesn’t hang forever. Request works = you’re online, fails or times out = offline. I’ve used this in production apps where I needed to know connectivity before letting users submit forms or sync data, and it’s been bulletproof.
totally agree! navigator.onLine can be misleading. what i do is ping a tiny file, like a favicon. if it fails, then ur def offline. wrap it in a try/catch block to handle errors and it works great!