Skip to main content

Network Information API - 提供有关系统网络连接的信息

实验中
这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

Network Information API(网络信息 API)根据一般连接类型(例如,“wifi”、“蜂窝” 等)提供有关系统网络连接的信息。它可用于根据用户的连接选择高清内容或低清晰度内容。整个 API 包括添加 NetworkInformation 接口和 Navigator 接口的 Navigator.connection 属性。

备注: 此特性在 Web Worker 中可用

实例

检测连接变化

此实例监视用户连接的变化。

var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
var type = connection.effectiveType;

function updateConnectionStatus() {
console.log("连接类型由 " + type + " 改为 " + connection.effectiveType);
type = connection.effectiveType;
}

connection.addEventListener('change', updateConnectionStatus);

预加载大资源

连接对象对于决定是否预加载占用大量带宽或内存的资源很有用。此实例将在页面加载后立即调用,以检查可能不需要预加载视频的连接类型。如果找到蜂窝连接,则 preloadVideo 标志设置为 false。为简单起见,本示例仅测试一种连接类型。实际用例可能会使用 switch 语句或其他一些方法来检查 NetworkInformation.type 的所有可能值。无论 preloadVideo 值是多少,您都可以通过 NetworkInformation.effectiveType 属性来估计连接速度。

let preloadVideo = true;
var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
if (connection.effectiveType === 'slow-2g') {
preloadVideo = false;
}
}

接口

NetworkInformation

提供有关设备用于与网络通信的连接的信息,并提供一种在连接类型更改时通知脚本的方法。NetworkInformation 接口不能被实例化。它是通过 Navigator 接口访问的。

规范

规范
Network Information API

浏览器兼容性

NetworkInformation

桌面浏览器兼容性

特性ChromeEdgeFirefoxInternet ExplorerOperaSafari
基础支持617931不支持48不支持1
change 事件6179不支持不支持48不支持
downlink613793不支持不支持483不支持
downlinkMax614不支持不支持不支持不支持不支持
effectiveType6179不支持不支持48不支持
rtt615795不支持不支持485不支持
saveData6579不支持不支持52不支持
type614不支持31不支持不支持不支持
typechange 事件不支持不支持31不支持不支持不支持
在 Worker 中可用617931不支持48不支持

移动浏览器兼容性

特性AndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
基础支持5038未知31 — 99未知25不支持1
change 事件5038未知不支持2未知45不支持
downlink503383未知不支持未知253不支持
downlinkMax5038未知不支持未知45不支持
effectiveType5038未知不支持未知45不支持
rtt505385未知不支持未知255不支持
saveData6565未知不支持未知47不支持
type5038未知31 — 99未知45不支持
typechange 事件不支持386未知31 — 99未知256不支持
在 Worker 中可用5038未知53 — 99未知45不支持

1. See bug 185697.

2. On Firefox, the event handler property corresponding to the change event is ontypechange.

3. The value is never greater than 10 Mbps, as a non-standard anti-fingerprinting measure.

4. Only supported in Chrome OS

5. The value is never greater than 3000 ms, as a non-standard anti-fingerprinting measure.

6. Removal proposed in bug 699892.

桌面浏览器兼容性

特性ChromeEdgeFirefoxInternet ExplorerOperaSafari
基础支持617931不支持48不支持2

移动浏览器兼容性

特性AndroidChrome for AndroidEdge mobileFirefox for AndroidIE mobileOpera AndroidiOS Safari
基础支持5038未知14 — 991未知37不支持2

1. The Network API is enabled by default. Can be disabled using the dom.netinfo.enabled preference.

2. See bug 185697.

相关链接