Battery Status API
Battery Status API,通常被称为 Battery API,提供有关系统电池电量水平的信息,并让你在电池电量或充电状态发生变化时收到触发的事件通知。这可用于调整应用程序的资源使用情况,以在电池电量不足时减少电池消耗,或在电池电量耗尽之前保存更改以防止数据丢失。
备注:
此 API 在 Web Worker 中不可用(未通过 WorkerNavigator
暴露)。
接口
BatteryManager
-
提供有关系统电池电量的信息。
其他接口的扩展
-
返回一个兑现一个
BatteryManager
对象的Promise
。
示例
在此示例中,我们观察充电状态的变化(无论是否插入电源并充电)以及电池电量和时间的变化。这通过监听 chargingchange
、levelchange
、chargingtimechange
、dischargingtimechange
事件完成。
js
navigator.getBattery().then((battery) => {
function updateAllBatteryInfo() {
updateChargeInfo();
updateLevelInfo();
updateChargingInfo();
updateDischargingInfo();
}
updateAllBatteryInfo();
battery.addEventListener("chargingchange", () => {
updateChargeInfo();
});
function updateChargeInfo() {
console.log(`电池是否充电中?${battery.charging ? "是" : "否"}`);
}
battery.addEventListener("levelchange", () => {
updateLevelInfo();
});
function updateLevelInfo() {
console.log(`电池电量:${battery.level * 100}%`);
}
battery.addEventListener("chargingtimechange", () => {
updateChargingInfo();
});
function updateChargingInfo() {
console.log(`电池充电时间:${battery.chargingTime}秒`);
}
battery.addEventListener("dischargingtimechange", () => {
updateDischargingInfo();
});
function updateDischargingInfo() {
console.log(`电池续航时间:${battery.dischargingTime}秒`);
}
});
参见规范中的示例。
规范
Specification |
---|
Battery Status API |
浏览器兼容性
api.BatteryManager
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
BatteryManager | ||||||||||||
charging | ||||||||||||
chargingTime | ||||||||||||
chargingchange event | ||||||||||||
chargingtimechange event | ||||||||||||
dischargingTime | ||||||||||||
dischargingtimechange event | ||||||||||||
level | ||||||||||||
levelchange event | ||||||||||||
Secure context required |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- Partial support
- Partial support
- No support
- No support
- Experimental. Expect behavior to change in the future.
- Has more compatibility info.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
api.Navigator.getBattery
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
getBattery | ||||||||||||||
Secure context required |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- No support
- No support
- Experimental. Expect behavior to change in the future.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.