1. navigator.onLine方法监听,返回布尔值。要么在线,要么离线断网

function updateOnline() {
   console.log(navigator.onLine ? 'online' : 'offline');
}

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

兼容性还可以

2. navigator.connection 方法监听从2G/3G/4G之间的切换,手机支持率很高,谷歌内核/QQ内核/火狐内核都支持

const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

connection.addEventListener('change', () => {
    // connection.effectiveType返回的是具体的网络状态:4g/3g/2g
    console.log(connection.effectiveType);
});

原文:思否《JS中监听网络状况的常用方法》--- https://segmentfault.com/a/1190000023957246