JS-判断用户当前网络状态

方法一:web的online offline事件

Online_and_offline_events | MDN

navigator.onLine | MDN
navigator.online会返回浏览器的联网状态。在线返回true,离线返回false
一旦浏览器的联网状态发生改变,该属性值也会随之变化。
当用户点击链接或者脚本进行网络请求时,如果发现浏览器连接不上互联网,则该属性会被赋值为false
(各浏览器对该属性的实现略有不同)
语法:online = window.navigator.online;

1
2
3
4
5
6
// 🌰栗子
if (navigator.onLine) {
alert('online')
} else {
alert('offline');
}

方法二:ajax请求

如果offline,我们可以catch到一个error对象。

1
2
3
4
5
6
7
8
9
10
this.$axios({
method: 'xxx',
url: 'xxx/xxx'
...
}).then((res) => {
...
}).catch((error) => {
console.log(error)
})
// Network Error: ...