Answer the question
In order to leave comments, you need to log in
How to check the presence of the Internet in JavaScript - online or offline?
Looking for a solution. So far I am using this function:
function isOnline() {
var url = 'http://example.com/?' + Date.now(); // url любой
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false); // sync
try {
xhr.send(); // Когда нет интернета - происходит "NetworkError" и срабатывает catch{}
return xhr.status === 200 ? true : false;
} catch (err) {
return false;
}
}
Answer the question
In order to leave comments, you need to log in
https://levelup.gitconnected.com/detecting-online-...
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
function updateOnlineStatus(event) {
var condition = navigator.onLine ? "online" : "offline";
document.body.className = condition;
}
async function isOnline() {
try {
await fetch("https://google.com");
return true;
}
return false;
}
Your solution can be made more interesting for the user.
For example, Network Error often means that there is no connection to the nearest WiFi/Router.
Sometimes this is an undocumented status of 0.
Status 503 means that the desired server is not available.
Accordingly, the user can be more accurately informed and advised differently depending on the result.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question