Battery Status API

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

Battery Status API,通常被称为 Battery API,提供有关系统电池电量水平的信息,并让你在电池电量或充电状态发生变化时收到触发的事件通知。这可用于调整应用程序的资源使用情况,以在电池电量不足时减少电池消耗,或在电池电量耗尽之前保存更改以防止数据丢失。

备注: 此 API 在 Web Worker不可用(未通过 WorkerNavigator 暴露)。

接口

BatteryManager

提供有关系统电池电量的信息。

其他接口的扩展

返回一个兑现一个 BatteryManager 对象的 Promise

示例

在此示例中,我们观察充电状态的变化(无论是否插入电源并充电)以及电池电量和时间的变化。这通过监听 chargingchangelevelchangechargingtimechangedischargingtimechange 事件完成。

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 GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
BatteryManager
charging
chargingTime
chargingchange event
chargingtimechange event
dischargingTime
dischargingtimechange event
level
levelchange event
Secure context required
Experimental

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.

api.Navigator.getBattery

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
getBattery
Secure context required
Experimental

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.

参见