Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Battery Status API

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

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

範例

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

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 Status Comment
Battery Status API Candidate Recommendation Initial specification.

瀏覽器相容性

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support Not supported
Chrome on Android: crbug.com/135863
Chrome OS: crbug.com/122593
10 (10) moz [1]
16 (16) (without prefix) [2]
Not supported Not supported Not supported
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? Not supported 10.0 (10) moz [1]
16.0 (16) (without prefix) [2]
Not supported Not supported Not supported

Gecko notes

[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled to true. Starting with Firefox 11.0, mozBattery is enabled by default.

[2] The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 (Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15 / Firefox OS 1.0.1).

另請參閱

文件標籤與貢獻者

 此頁面的貢獻者: MashKao
 最近更新: MashKao,