Battery Status API
Battery Status API 也就是所謂的 Battery API,將提供系統電池充電容量的資訊,並在電池容量變化時送出事件,以通知使用者。此 API 可調整 Apps 的資源耗用量,在電力偏低時縮減耗電量;或可在電力耗盡之前儲存檔案,避免資料遺失。
Battery Status API 是以 window.navigator.battery
屬性 (為 BatteryManager
物件) 而擴充了 window.navigator
,並新增數項可讓使用者接收的新事件,以隨時監控電池狀態。
範例
在此範例中,我們將分別監聽 chargingchange 與 levelchange 事件,而看到充電狀態 (不論是否插電進行充電) 與電池容量的變化。
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 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.
另請參閱
- 部落格文章 - Using the Battery API
- David Walsh 所寫的 JavaScript Battery Api
- battery.js - 跨瀏覽器 wrapper
BatteryManager
navigator.battery
測試你的瀏覽器是否支援 Battery Status API。可掃 QR Code: