Last active
August 31, 2022 17:35
-
-
Save joebobmiles/ef2cceae16abe0edf39709cf3d4eb188 to your computer and use it in GitHub Desktop.
Check that a Page is Online
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
/* | |
For reactive applications, IS_ONLINE could be replaced with a set() call that | |
alters the store. | |
*/ | |
let IS_ONLINE = false; | |
const checkOnlineStatus = async () => { | |
if (!navigator.onLine) return false; | |
else { | |
try { | |
const request = await fetch("/some/status/endpoint"); | |
return request.status >= 200 && request.status < 300; | |
} | |
catch { | |
return false; | |
} | |
} | |
} | |
window.addEventListener("load", async () => { | |
IS_ONLINE = await checkOnlineStatus(); | |
setInterval( | |
async () => { | |
if (!IS_ONLINE) { | |
IS_ONLINE = await checkOnlineStatus(); | |
} | |
}, | |
30000 // check every 30 seconds. | |
); | |
}); | |
window.addEventListener("offline", () => { | |
IS_ONLINE = false; | |
}); | |
window.addEventListener("online", async () => { | |
IS_ONLINE = await checkOnlineStatus(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment