- onLine API (手机端和PC端实现较好)
- connection API (PC端的某些高级版本支持)
onLine:一个属性两个事件
// 一个属性 true false
var online = navigator.onLine;
// 两个事件
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
connection:一个对象一个事件
// type 网络类型
bluetooth: 蓝牙
cellular: 蜂窝网络(e.g., EDGE, HSPA, LTE, etc.)
ethernet: 以太网
none: 无连接
mixed: 多类型混合
other: 类型可知,但不可枚举
unknown: 有链接,但类型未知
wifi: Wi-Fi
wimax: WiMAX
// effectiveType 有效连接类型
'2g'
'3g'
'4g'
'slow-2'
// rtt 往返时间(round-trip time)
demo
{
// 获取网络状态
onGetStatus () {
if(!this.canUseConnection) return this.$message.error('浏览器不支持navigator.connection';
this.updateConnectionStatus();
},
// 绑定事件监听
bindEvents () {
let self = this;
window.addEventListener('online', e => self.updateOnlineStatus());
window.addEventListener('offline', e => self.updateOnlineStatus());
if(navigator.connection) {
let timer = null;
navigator.connection.addEventListener('change', e => {
timer && clearTimeout(timer);
timer = setTimeout(() => {
self.updateConnectionStatus(e);
}, 500);
});
}
},
// 更新onLine状态
updateOnlineStatus () {
this.online = navigator.onLine;
if(this.online) {
this.$message.success('有网');
} else {
this.$message.error('掉线');
}
},
// 更新connection状态
updateConnectionStatus (e) {
this.connection = navigator.connection || initConnection;
this.$notify.info({
title: '提示',
message: '当前网络:' + (e ? e.currentTarget.type : this.connection.type || 'unknown')
});
}
}