问题
navigator.onLine is still returning true when I turn off Wi-Fi (Airport on my notebook in OS X). This is counterintuitive behavior. But when I set "work offline" in a browser like Firefox, it correctly returns false. Is this expected?
alert(navigator.onLine ? "online" : "offline");
回答1:
Yes. The browser doesn't provide network connectivity information to the page, but rather uses Work Offline's status as the value.
回答2:
Use the window.addEventListener to detect network updates:
window.addEventListener('online', amIOnline);
window.addEventListener('offline', amIOffline);
function amIOnline(){
console.log('online');
}
function amIOffline(){
console.log('offline');
}
来源:https://stackoverflow.com/questions/2779367/navigator-online-still-true-when-turning-off-wifi-false-when-set-work-offline