JavaScript — Detect If a Device Battery Is Charging

One of our projects is a point of sale (POS) application. This POS is a web app and served in a fullscreen browser on a tablet. We can get an overview of the POS with the help of a dashboard. The dashboard displays information about sales and the tablet itself, like the battery level and whether it’s charging or not.

This tutorial shows you how to use the JavaScript battery API to detect if a device is charging.

JavaScript Series Overview

Detect If the Battery Is Charging

The JavaScript battery API provides information about the system’s battery and its charging status. The battery API is available via the global navigator object. The navigator.getBattery() method returns a Promise that resolves to a battery manager instance.

The battery manager provides property and events to detect whether a system is charging. The battery.charging property returns a boolean value telling you whether the system is currently charging:

navigator.getBattery().then(battery => {  
  console.log(battery.charging)
  // true
})

Listen for the chargingchange Event

You can also listen for changes on the charging property. Use the battery manager’s onchargingchange property and assign a function that will be called when the battery charging status changes:

navigator.getBattery().then(battery => {  
  battery.onchargingchange = () => {
    // check `battery.charging` property change

    console.log(`Battery is charging: ${battery.charging}`)
  }
})

Detect If a Battery Is Charging But Losing Power

A situation that can happen is that the battery is charging, but the device is losing power. The battery level decreases even though the tablet is plugged in and the battery.charging property is true.

To notice situations where the tablet is losing power despite charging, we added a check to the POS. The POS stores the previous battery level in local storage and compares it against the current battery level at a given interval. We’re using a heartbeat mechanism that checks the battery level every 2 minutes.

Here’s our simplified code to check if the tablet might run out of battery:

const cacheKey = `pos-battery-level-cache-key`;

navigator.getBattery().then(battery => {  
  const previousBatteryLevel = Number(localStorage.getItem(cacheKey) || 0);

  const batteryLevelDiff = battery.level - previousBatteryLevel;
  const isChargingButLosingPower = battery.charging && batteryLevelDiff < 0;

  localStorage.setItem(cacheKey, battery.level);

  if (isChargingButLosingPower) {
    // ⚡️ handle this case
  }
})

We’re using the global localStorage object in the code snippet. All modern browsers support local storage. Depending on your audience and whether they’re using older browser versions, you may need to check if localStorage is available. We have a related tutorial available here on Future Studio:

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.