Detecting Battery Status in JavaScript.

Learn how to detect battery status in JavaScript using Battery Manager.

Image by Brett Jordan.

The BatteryManager interface provides ways to get information about the system’s battery charge level.

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.

First, let’s check if the browser supports battery 🔋

let isBatterySupported = 'getBattery' in navigator;
if(!isBatterySupported) {
console.log("Battery not supported");
}

Once our browser supports the BatteryManager, we can get that from getBattery method in navigator object, which will return a promise once the promise is resolved we will get the BatteryManager object, which has four properties and four events

Properties

charging - Determines the charging state (true/false)
level - Battery Percentage
chargingTime -  the remaining time in seconds until the battery is fully charged, or 0 if the battery is already fully charged.
dischargingTime -  the remaining time in seconds until the battery is completely discharged and the system will suspend.

Events

onchargingchange - triggered when charging state changed
onlevelchange - triggered when level of battery changed
onchargingtimechange - This event is sent when the battery charging time is updated
ondischargingtimechange - This event is sent when the battery charging time is updated

Let’s get the Battery object

let batteryPromise = navigator.getBattery();
batteryPromise.then(batteryCallback);

function batteryCallback(batteryObject) {
   printBatteryStatus(batteryObject);
}
function printBatteryStatus(batteryObject) {
    console.log("IsCharging", batteryObject.charging);
    console.log("Percentage", batteryObject.level);

console.log("charging Time", batteryObject.chargingTime);
    console.log("DisCharging Time", batteryObject.dischargingTime);
}

Result for above code

Note

The value of discharging time is Infinity. if the battery is currently charging rather than discharging, or if the system is unable to report the remaining discharging time.

Adding Events

Now let’s add event to detect charge level change and charge state change in our battery callback function

function batteryCallback(batteryObject) {
    printBatteryStatus(batteryObject);
    batteryObject.addEventListener('chargingchange', function(ev
{
printBatteryStatus(batteryObject);
});
batteryObject.addEventListener('levelchange', function(ev
{
printBatteryStatus(batteryObject);
});
}

The above event will be triggered once the level of charge changes or charging state changes.

Reference

MDN: BatteryManager.

Leave a comment

Design a site like this with WordPress.com
Get started