M
M
med1um2020-07-16 16:41:10
JavaScript
med1um, 2020-07-16 16:41:10

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;
    }
}

Mandatory requirement: IE11 support.

What do you think? Maybe there are better ways? What method are you using?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
profesor08, 2020-07-17
@med1um

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;
}

Method 2
async function isOnline() {
  try {
    await fetch("https://google.com");
    return true;
  }

  return false;
}

V
Viktor Sirotin, 2020-07-27
@visirok

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 question

Ask a Question

731 491 924 answers to any question