Created
March 26, 2022 11:40
-
-
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
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
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