Battery Status API

Battery Status API 也就是所謂的 Battery API,將提供系統電池充電容量的資訊,並在電池容量變化時送出事件,以通知使用者。此 API 可調整 Apps 的資源耗用量,在電力偏低時縮減耗電量;或可在電力耗盡之前儲存檔案,避免資料遺失。

Battery Status API 是以 window.navigator.battery 屬性 (為 BatteryManager 物件) 而擴充了 window.navigator,並新增數項可讓使用者接收的新事件,以隨時監控電池狀態。

範例

在此範例中,我們將分別監聽 chargingchangelevelchange 事件,而看到充電狀態 (不論是否插電進行充電) 與電池容量的變化。

js
var battery =
  navigator.battery || navigator.mozBattery || navigator.webkitBattery;

function updateBatteryStatus() {
  console.log("Battery status: " + battery.level * 100 + " %");

  if (battery.charging) {
    console.log("Battery is charging");
  }
}

battery.addEventListener("chargingchange", updateBatteryStatus);
battery.addEventListener("levelchange", updateBatteryStatus);
updateBatteryStatus();

另可參閱規格所提供之範例

規格

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.

另請參閱