The navigator.onLine solution was part of the way there, but it would not give correct results if a computer was connected to a wifi router (that itself was not connected to the internet).
I discovered that CORS was the problem with my approach, and thanks to the people in the comments, I discovered a better way that used an image resource (like @Alnitak said). This answer was helpful in finding out how to handle the image loading and error callbacks.
Here is some simple code to show how I did it.
See the Pen
InternetConnection by Daniel (
@Diomoid) on
CodePen.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>InternetConnection</title>
<script src="InternetConnection.js" type="text/javascript"></script>
</head>
<body onload="initialize();">
<h1 id="status"></h1>
</body>
</html>
JS
var internetAccess = true;
// Goes to Google and tries to get an image, changes a flag, then calls to update view
function checkInternet(){
var img = new Image();
img.onload = function(){
internetAccess = true;
updateView();
};
img.onerror = function(){
internetAccess = false;
updateView();
};
// The browser will cache images (and you'll always get a successful 'onload') unless you request a 'dummmy' query ('?dummy=UNIQUE_NUMBERS') so that every image is unique.
img.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'+"?dummy="+new Date().getTime();
}
function updateView(){
var isOnline = navigator.onLine && internetAccess;
if(isOnline){
console.log("Connected!");
document.body.bgColor = 'darkgreen';
document.getElementById("status").innerHTML = "CONNECTED :)";
// Retest connection to ensure is truly connected... I commented this out since I do not really want to constantly check in my case (I just register a click listener so that I don't have hundreds of requests of small images over an hour if I leave the webpage running).
// checkSpawner();
}else{
console.log("NOT connected");
document.body.bgColor = 'yellow';
document.getElementById("status").innerHTML = "NOT CONNECTED :(";
// Retest connection until it succeeds
checkSpawner();
}
}
// Check internet connection every 5 seconds
function checkSpawner(){
console.log("checking for internet...");
setTimeout(checkInternet, 5000);
}
// Setup listeners for when the connection is disrupted
function initialize(){
window.addEventListener("online", checkInternet);
window.addEventListener("offline", checkInternet);
checkInternet();
}