Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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";
});
@aishtiaq7

This comment has been minimized.

Copy link

@aishtiaq7 aishtiaq7 commented Apr 26, 2021

when fetching using :
await fetch("/1pixel.png");

it returns this error:
GET http://127.0.0.1:5500/1pixel.png 404 (Not Found)

@dtknepper

This comment has been minimized.

Copy link

@dtknepper dtknepper commented May 8, 2021

when fetching using :
await fetch("/1pixel.png");

it returns this error:
GET http://127.0.0.1:5500/1pixel.png 404 (Not Found)

I believe that is because you do not have a file with that name in your directory. If you create a file of 1 pixel in height and width name it pixel1.png and place it in the same folder as this JS file the problem should be solved.

@brnhache

This comment has been minimized.

Copy link

@brnhache brnhache commented May 10, 2021

when fetching using :
await fetch("/1pixel.png");
it returns this error:
GET http://127.0.0.1:5500/1pixel.png 404 (Not Found)

I believe that is because you do not have a file with that name in your directory. If you create a file of 1 pixel in height and width name it pixel1.png and place it in the same folder as this JS file the problem should be solved.

If it was referencing a local file, how would that indicate an internet connection?

@dtknepper

This comment has been minimized.

Copy link

@dtknepper dtknepper commented May 10, 2021

when fetching using :
await fetch("/1pixel.png");
it returns this error:
GET http://127.0.0.1:5500/1pixel.png 404 (Not Found)

I believe that is because you do not have a file with that name in your directory. If you create a file of 1 pixel in height and width name it pixel1.png and place it in the same folder as this JS file the problem should be solved.

If it was referencing a local file, how would that indicate an internet connection?

It wouldn't. But thats for local developement only. Just make sure you put the same files online once you upload it to a server.

@DArtagnan021

This comment has been minimized.

Copy link

@DArtagnan021 DArtagnan021 commented Jul 9, 2021

what can i use instead of await fetch("/1pixel.png") in the following code of yours.Its gvien me error while for initialization.
Below down its my..

<script> const checkOnlineStatus = async () => { try { const online = ""; 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("<%=lbl_company.ClientID%>"); statusDisplay.textContent = result; if (result == true) { document.getElementById("<%=btnpdf.ClientID%>").style.display = "none"; } else { document.getElementById("<%=btnpdf.ClientID%>").style.display = "block"; } }, 5000); // 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("<%=lbl_company.ClientID%>"); statusDisplay.textContent = (await checkOnlineStatus()) ? alert("Online") : alert("OFFline"); }); </script>
@DesignByOnyx

This comment has been minimized.

Copy link

@DesignByOnyx DesignByOnyx commented Jul 20, 2021

I recommend using a self-calling timeout rather than setInterval because the request might take a long time on a very slow connection, and you could potentially stack up requests in a way you don't want:

(function pollOnlineStatus() {
  setTimeout(async () => {
    const result = await checkOnlineStatus();
    const statusDisplay = document.getElementById("status");
    statusDisplay.textContent = result ? "Online" : "OFFline";
    pollOnlineStatus(); // self-calling timeout is better than setInterval for this
  }, 3000);
})()

Furthermore, you can consider a really slow internet to be "offline" with the following:

const checkOnlineStatus = () => {
  return new Promise(async (resolve) => {
    let resolved = false;
    // requests longer than 5s are considered "offline"
    const timer = setTimeout(() => {
      resolved = true;
      resolve(false);
    }, 5000);

    try {
      const online = await fetch("/1pixel.png");
      clearTimeout(timer);
      if (!resolved) {
        resolve(online.status >= 200 && online.status < 300); // either true or false
      }
    } catch (err) {
      if (!resolved) {
        resolve(false); // definitely offline
      }
    }
  });
};
@jacobcollinsdev

This comment has been minimized.

Copy link

@jacobcollinsdev jacobcollinsdev commented Aug 25, 2021

I've found that even when I tick "Offline" in Chrome service workers, the ajax response is true... anyone else had this?

const checkOnlineStatus = async () => {
    try {
      const online = await fetch("/img/1pixel.png",{
          mode: 'no-cors'
      });
      return online.status >= 200 && online.status < 300; // either true or false
    } catch (err) {
      return false; // definitely offline
    }
};

setInterval(async () => {
    const result = await checkOnlineStatus();
    console.log(result)
    const statusDisplay = document.querySelector('.internet-connection');
    statusDisplay.textContent = result ? "Online" : "OFFline";
}, 2000);
@jacobcollinsdev

This comment has been minimized.

Copy link

@jacobcollinsdev jacobcollinsdev commented Aug 25, 2021

I've found that even when I tick "Offline" in Chrome service workers, the ajax response is true... anyone else had this?

const checkOnlineStatus = async () => {
    try {
      const online = await fetch("/img/1pixel.png",{
          mode: 'no-cors'
      });
      return online.status >= 200 && online.status < 300; // either true or false
    } catch (err) {
      return false; // definitely offline
    }
};

setInterval(async () => {
    const result = await checkOnlineStatus();
    console.log(result)
    const statusDisplay = document.querySelector('.internet-connection');
    statusDisplay.textContent = result ? "Online" : "OFFline";
}, 2000);

Solved this by adding cache: 'no-cache' beneath mode:'no-cors'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment