I've a tried a lot of things to check the internet connection of the users of my app. My first researches brought me to the navigator.onLine
method. It works sometimes. But sometimes it doesn't. Of course it's not new, I have seen multiples people complaining about that.
Then I tried the XHR request. It was working on every devices, whatever the internet navigator (not like the previous method). But I got some warnings from Chrome and Firefox cos it was synchronous and may slow the whole app.
So I converted my function to an asynchronous function :
function verification() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "//" + window.location.hostname + "/ressources/favicon.ico?rand=" + Date.now(), true);
xhr.onload = function (e) {
if (xhr.readyState === 4 && xhr.status === 200) {
reconnection();
}
};
xhr.onerror = function (e) {
deconnexion();
};
xhr.send(null);
}
The idea is simple, I check if I can access to the favicon (with a rand to make it unique and avoid cache ressource). If the request is a success then I consider I'm connected. If not, I'm not connected. So far, it seems to work pretty well.
My question is : is it the best way to do that with pure JS ? Or should I maybe consider using fetch
? Or is there a better way I didn't find ?