Battery Status API in JavaScript Explained

The Battery Status API, also known as the Battery API, allows web developers to access system battery information and monitor changes in a device’s power levels using JavaScript. This article explains how the API works, the specific properties it exposes through the BatteryManager interface, how to implement it using modern JavaScript, and the real-world use cases along with privacy-related browser support considerations.

What Is the Battery Status API?

The Battery Status API provides a standardized way for web applications to determine the battery state of the hosting device. Accessed via the asynchronous method navigator.getBattery(), it returns a Promise that resolves with a BatteryManager object. This object contains data about the current power state, charging status, and remaining time before the battery is depleted or fully charged.

Core Properties of the BatteryManager Interface

The BatteryManager interface exposes four read-only properties:

How to Read Battery Status with JavaScript

To read device power levels, use navigator.getBattery() to resolve the BatteryManager object and read its properties.

navigator.getBattery().then((battery) => {
  console.log(`Battery level: ${battery.level * 100}%`);
  console.log(`Is charging: ${battery.charging ? "Yes" : "No"}`);
  console.log(`Charging time: ${battery.chargingTime} seconds`);
  console.log(`Discharging time: ${battery.dischargingTime} seconds`);
});

Listening for Power Level Changes

The BatteryManager interface inherits from EventTarget, enabling event listeners to detect real-time changes in power status:

navigator.getBattery().then((battery) => {
  // Update UI when battery percentage changes
  battery.addEventListener('levelchange', () => {
    console.log(`New battery level: ${battery.level * 100}%`);
  });

  // Update UI when charger is plugged/unplugged
  battery.addEventListener('chargingchange', () => {
    console.log(`Charging state changed: ${battery.charging}`);
  });
});

Practical Applications

Monitoring device power enables applications to dynamically optimize resource consumption:

Browser Support and Privacy Concerns

While the API was designed to help conserve energy, it introduced user privacy and fingerprinting risks. High-precision battery readings allowed third-party trackers to correlate and identify user sessions across different browsing contexts.

As a result, major browsers handle the API differently:

Before calling the API in production environments, always check for support:

if ('getBattery' in navigator) {
  navigator.getBattery().then((battery) => {
    // API is supported
  });
} else {
  // API is not supported on this browser
}