Skip to content

Instantly share code, notes, and snippets.

@ToniMaunde
Created March 26, 2022 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ToniMaunde/9c6c35dd004d1b99f3b5c75b2d90d68c to your computer and use it in GitHub Desktop.
Save ToniMaunde/9c6c35dd004d1b99f3b5c75b2d90d68c to your computer and use it in GitHub Desktop.
utility code a friend shared with me to check the connectivity status of the user
const isOnline = async ():Promise<boolean> => {
// Make a request to any host as long as it is a URL and not an IP in order to check DNS too
try {
await fetch("checkip.amazonaws.com");
return true;
} catch (error) {
return false;
}
};
window.addEventListener("load", async (event) => {
// navigator.onLine checks if the user is connected to a network and not necessarily if he has
// Internet access
if (navigator.onLine) {
// making a request to check if the user has Internet access
const hasAccessToInternet = await isOnline();
if (hasAccessToInternet) {
console.log("online")
}
} else console.log("offline");
});
// log when the user becomes offline
window.addEventListener("offline", (event) => {
console.log("offline");
});
// confirm that the user has Internet access when "onLine" event is fired
window.addEventListener("online", async (event) => {
const hasAccessToInternet = await isOnline();
if (hasAccessToInternet) {
console.log("definitely online")
}
else console.log("not online");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment