简体   繁体   中英

The onLine API isn't working in any browser

navigator.onLine is always returning true and the online and offline events are not firing for this simple piece of code either in Firefox 66.0.1 or Chrome 73 on 64-bit Windows 7.

let statusElement = document.getElementById("status");
statusElement.innerText = navigator.onLine ? "online." : "offline.";

function updateStatus(event) {
    statusElement.innerText = `${event.type}.`;
}

window.addEventListener('offline', updateStatus);
window.addEventListener('online', updateStatus);

Where the HTML is simple this:

<h1>You are <span id = "status"></span></h1>

I just changed my machine and the same code works on a different machine perfectly.

I figured the reason it didn't work on the old machine was because I had an IP Address that was always active. It was an IP that was allotted to my machine by Oracle's Virtual-Box. I found this out by running ipconfig on my machine and saw that no matter what I did, I always had the Virtual-Box using my Ethernet card.

And since the documentation for this feature says that it will show a status of online if the machine is connected to the network, implying to any network, ie if it has network access of any sort.

It is therefore inferred that this method is not terribly reliable if you want to really know if the user has an active Internet connection, though it does work for most of the cases.

Case solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM