AshKeys

Confessions and Confusions of Ashok M A. Personal and Professional Blog.

Ashok Mannolu Arunachalam, How toJS
Back

How to get the battery status of a device using JavaScript

The BatteryManager interface provides ways to get information about the system's battery charge level by interacting with Battery Status API

We can use the Battery Manager to detect

  • charging state
  • Battery percentage
  • Time needed to charge 100%
  • The remaining time until the battery is completely discharged.
js
let { getBattery } = navigator
if (!getBattery) {
// Check whether such function exists
console.warn('Battery Manager is not supported!')
} else {
navigator
.getBattery()
.then(({
level, charging, chargingTime, dischargingTime
}) => {
console.log('Percentage', level)
console.log('IsCharging', charging)
console.log('charging Time', chargingTime)
console.log('DisCharging Time', dischargingTime)
})
}
/**
Outputs:
Percentage 0.59
IsCharging false
charging Time Infinity (Because the device is not charging)
DisCharging Time 8280
**/

If we wish to get the status on change, we can add listeners for the respective properties. There is a function to do the same. \O/

  • onchargingchange
  • onchargingtimechange
  • ondischargingtimechange
  • onlevelchange

This feature has been deprecated from the web standards. But it is always fun know something new, is it not? ^_^