跳转到内容

网络状态监控

刀刀
0字
0分钟
2026/8/16

前端 window 内置 API 可监控用户网络状态、延迟和带宽。以下是该属性的介绍。

JS 前置知识:Navigator.connection

  • Navigatorconnection 属性

    实验性: 这是一项实验性技术 在将其用于生产之前,请仔细检查浏览器兼容性表格

    Navigator.connection 只读属性返回一个包含有关系统网络连接信息的 NetworkInformation 对象,例如用户设备的当前带宽或连接是否按流量计费。

    这可以用于基于用户的连接状态来选择高清晰度内容或低清晰度内容。

    值:一个 NetworkInformation 对象。包含的属性如下:

    • effectiveType :网络类型
    • rtt :延迟,单位是毫秒
    • downlink :带宽速度

    具体效果如下图所示:

    connection

  • Window:online 事件

    当浏览器能够访问网络,且 Navigator.onLine (en-US) 的值被设为 true 时,Window 接口的 online 事件将被触发。

    备注

    该事件不能用于确定某个网站可否访问。网站自身问题或防火墙都有可能阻止对特定网站的访问。

    是否冒泡
    是否可取消
    接口Event
    Event handler propertyononline
    js
    window.addEventListener('online', (event) => {
      console.log('You are now connected to the network.')
    })
    js
    window.ononline = (event) => {
      console.log('You are now connected to the network.')
    }

JS 网络状态监控效果实现

利用上述 API 实现效果:

js
function getNetworkInfo() {
  let info
  if (navigator.onLine) {
    info = {
      type: navigator.connection.effectiveType,
      rtt: navigator.connection.rtt,
      downlink: navigator.connection.downlink,
    }
  } else {
    type: 'offline'
  }

  return info
}

如何检测到信息变化呢?

  1. 如果是想要检测当前是否在线,可以通过 onlineoffline 事件实现。
  2. 如果想检测网络状态的变化,上面的方法不再适用,可以通过 navigator.connectionchange 方法实现。

代码如下:

js
window.addEventListener('online', () => {
  // ...
})

window.addEventListener('offline', () => {
  // ...
})

navigator.connection.addEventListener('change', () => {
  // ...
})

JS 网络状态监控总体效果

跳转预览:点击跳转

贡献者

The avatar of contributor named as duyidao duyidao
The avatar of contributor named as 平安喜乐 平安喜乐
The avatar of contributor named as v_duyilin v_duyilin
The avatar of contributor named as 刀刀 刀刀

页面历史

刀刀博客累计访客 人;文档累计访问量共