I want to implement offline mode for my web app and found that it can be done using online
and offline
events. I tried the following example from the MDN docs:
window.addEventListener("online", () => {
console.log("You are now connected to the network.");
});
window.addEventListener("offline", () => {
console.log("The network connection has been lost.");
});
However, the events are not triggering at all in my app. I tested this:
Surprisingly, it does work when I manually enable or disable the offline mode in DevTools.
As a workaround, I considered using this function:
async function checkRealOffline() {
try {
await fetch(";, { mode: "no-cors" });
console.log("Online.");
} catch (e) {
console.log("Offline.");
}
}
setInterval(checkRealOffline, 5000);
This works, but I still want to understand:
Any insights would be appreciated!
I want to implement offline mode for my web app and found that it can be done using online
and offline
events. I tried the following example from the MDN docs:
window.addEventListener("online", () => {
console.log("You are now connected to the network.");
});
window.addEventListener("offline", () => {
console.log("The network connection has been lost.");
});
However, the events are not triggering at all in my app. I tested this:
Surprisingly, it does work when I manually enable or disable the offline mode in DevTools.
As a workaround, I considered using this function:
async function checkRealOffline() {
try {
await fetch("https://example", { mode: "no-cors" });
console.log("Online.");
} catch (e) {
console.log("Offline.");
}
}
setInterval(checkRealOffline, 5000);
This works, but I still want to understand:
Any insights would be appreciated!
if (navigator.onLine) {
console.log("You are now connected to the network.");
} else {
console.log("The network connection has been lost.");
}
Navigator.onLine
switch? What you observed was expected. Please see https://developer.mozilla./en-US/docs/Web/API/Navigator/onLine. Your browser needs to check network connection, only then the online status changes. – Sergey A Kryukov Commented Mar 3 at 17:01