Network Information API

Network Information API 允许获取网络信息和监听网络信息更改,以及 Save Data API 提供了侦测用户流量使用倾向的方法

通过 navigator.connection 暴露 NetworkInformation 实例使用

获取网络信息

NetworkInformation 接口的 type 属性表示当前的网络连接的类型

NetworkInformation 接口的 effectiveType 属性表示当前的网络连接的状态

NetworkInformation 接口的 downlink 属性表示当前的 downlink 速度

NetworkInformation 接口的 downlinkMax 属性表示当前最大的 downlink 速度

NetworkInformation 接口的 rtt 属性表示当前的 RTT 参数

1
2
3
4
5
const type = navigator.connection.type
const effectiveType = navigator.connection.effectiveType
const downlink = navigator.connection.downlink
const downlinkMax = navigator.connection.downlinkMax
const rtt = navigator.connection.rtt

监听网络信息

NetworkInformation 接口的 change 事件在网络信息更新时触发

1
navigator.connection.addEventListener('change', () => { /* to do something */ })

类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
interface Navigator {
readonly connection: NetworkInformation
}

interface WorkerNavigator {
readonly connection: NetworkInformation
}

interface NetworkInformation extends EventTarget {
readonly type: ConnectionType
readonly effectiveType: EffectiveConnectionType
readonly downlinkMax: number
readonly downlink: number
readonly rtt: number
readonly saveData: boolean
onchange: ((this: NetworkInformation, ev: Event) => any) | null
}

interface NetworkInformationEventMap {
change: Event
}

type ConnectionType = 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'unknown'

type EffectiveConnectionType = 'slow-2g' | '2g' | '3g' | '4g'

链接

发布于

2023-10-26

更新于

2023-12-18

许可协议

评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...