Skip to content

Instantly share code, notes, and snippets.

@gitdagray
Last active March 14, 2024 20:55
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save gitdagray/f310be81be217750fc9d2b233e2ae70c to your computer and use it in GitHub Desktop.
Save gitdagray/f310be81be217750fc9d2b233e2ae70c to your computer and use it in GitHub Desktop.
Online / Offline Status Detection w/ Async & Await
/* ********** 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";
});
@MikeGads
Copy link

MikeGads commented Dec 3, 2022

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