Last active
March 14, 2024 20:55
-
-
Save gitdagray/f310be81be217750fc9d2b233e2ae70c to your computer and use it in GitHub Desktop.
Online / Offline Status Detection w/ Async & Await
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
/* ********** Online / Offline Detection ********** */ | |
// Request a small image at an interval to determine status | |
// ** Get a 1x1 pixel image here: http://www.1x1px.me/ | |
// ** Use this code with an HTML element with id="status" | |
const checkOnlineStatus = async () => { | |
try { | |
const online = await fetch("/1pixel.png"); | |
return online.status >= 200 && online.status < 300; // either true or false | |
} catch (err) { | |
return false; // definitely offline | |
} | |
}; | |
setInterval(async () => { | |
const result = await checkOnlineStatus(); | |
const statusDisplay = document.getElementById("status"); | |
statusDisplay.textContent = result ? "Online" : "OFFline"; | |
}, 3000); // 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"; | |
}); |
I implemented this React, with a bit of modification with the request to the server to fetch HEAD only to the root URL.
Please check the following link:
https://codesandbox.io/s/check-online-offline-status-44ju8p?file=/src/App.tsx
You link is dead, please update
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tell them to go to https://commons.wikimedia.org/wiki/File:1x1.png