battery
Reads device battery level and charging state via the Battery Status API.
Import: @rtorcato/browser-common/battery
The Battery Status API is Chromium-only and the spec is dormant โ getBatteryManager()
resolves to undefined where unsupported, so guard with isBatteryApiAvailable() first.
Browser supportโ
| API | Chrome | Edge | Firefox | Safari | iOS Safari | Baseline |
|---|---|---|---|---|---|---|
Navigator.getBattery | โ 38+ | โ 79+ | โ removed in 52 | โ | โ | Limited |
Needs: secure context (HTTPS)
โ
supported ยท โ partial ยท โ not supported ยท [n] see note. Generated from MDN browser-compat-data and web-features. caniuse: Navigator.getBattery
Exampleโ
import {
isBatteryApiAvailable,
getBatteryManager,
onBatteryLevelChange,
} from '@rtorcato/browser-common/battery'
if (isBatteryApiAvailable()) {
const battery = await getBatteryManager()
const off = battery && onBatteryLevelChange(battery, () => console.log(battery.level))
off?.()
}
Exportsโ
isBatteryApiAvailable()โ feature checkgetBatteryManager()โ resolves to theBatteryManager, orundefinedonBatteryLevelChange(battery, callback)โ subscribes to level changes, returns an unsubscribe functiononBatteryChargingChange(battery, callback)โ subscribes to charging state changes, returns an unsubscribe function
See the API reference for full signatures.