Last active
April 26, 2021 14:31
-
-
Save aishtiaq7/182eb87b5bfd658f89484b7a29f392ae to your computer and use it in GitHub Desktop.
Test to see if your client side has a internet Connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Title HERE</title> | |
<link type="text/css" rel="stylesheet" href="./styles.css"> | |
</head> | |
<body> | |
<h2>Connection Status:<span id="status"></span></h2> | |
</body> | |
<script src="./script.js"></script> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log("ready mama"); | |
// To print images in console logs | |
//const url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Bodashtart_1.png/552px-Bodashtart_1.png'; | |
//console.log('%c ', `font-size:600px; background:url(${url}) no-repeat; backdround-size: contain ;`); | |
const checkOnlineStatus = async () => { | |
try { | |
const online = await fetch("https://jsonplaceholder.typicode.com/todos/1"); | |
var connectionStatus = online.status >= 200 && online.status < 300; | |
console.log(`connectionIsFound:${connectionStatus}`); | |
return connectionStatus ; // either true or false | |
} catch (err) { | |
console.log('...catch block executed'); | |
return false; // definitely offline | |
} | |
}; | |
setInterval(async () => { | |
const result = await checkOnlineStatus(); | |
const statusDisplay = document.getElementById("status"); | |
statusDisplay.textContent = result ? "Online" : "OFFline"; | |
}, 1000); // probably too often, try 30000 for every 30 seconds | |
// forgot to include async load event listener in the video! | |
window.addEventListener("load", async (event) => { | |
const statusDisplay = document.getElementById("status"); | |
statusDisplay.textContent = (await checkOnlineStatus()) | |
? "Online" | |
: "OFFline"; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment