I am using navigator.online to check if internet is offline or online (I know its downside but still its relevant to my project), how can I alert a message "Internet is back" and perform some actions as soon as internt comes again
CodePudding user response:
You could use the online or offline event. Resource
window.addEventListener("online", () => {});
window.addEventListener("offline", () => {});
CodePudding user response:
You can refer to this solution, converted to JS (original post link :https://stackoverflow.com/a/70737477/6696948)
window.isDisconnected = false;
function setIsDisconnected(val) {
window.isDisconnected = val;
document.body.textContent = !window.isDisconnected ? "online" : "offline"
}
function init() {
handleConnectionChange();
window.addEventListener("online", handleConnectionChange);
window.addEventListener("offline", handleConnectionChange);
function handleConnectionChange() {
const condition = navigator.onLine ? "online" : "offline";
if (condition === "online") {
const webPing = setInterval(() => {
fetch("https://jsonplaceholder.typicode.com/todos/1", {
mode: "no-cors"
})
.then(() => {
setIsDisconnected(false);
clearInterval(webPing);
})
.catch(() => setIsDisconnected(true));
}, 2000);
return;
}
setIsDisconnected(true);
}
};
init()