The Battery API in HTML5 with JavaScript and HTML5

- 👤 Andrés Cruz

🇪🇸 En español

The Battery API in HTML5 with JavaScript and HTML5

See example Download source

If you've ever wanted to adjust your web application based on the device's battery level — whether to activate a dark mode, reduce animations, or simply display a "running out of battery" warning — then the HTML5 Battery API is exactly what you need. Although its current support is very limited (yes, Firefox, I still love you), it remains an interesting API that lets you work with device energy information directly from JavaScript.

Throughout this article, I will explain how it works, its events, its limitations, and several real-life cases where I have used it. Let's get all the juice we can from this API.

One of the many APIs for JavaScript that allows working with mobile device components is the Battery API, which is accessible through the navigator.battery object; this API provides information about the mobile device's current charge level; it also provides a series of events that are executed when the mobile device changes from one state to another, for example:

  • If the mobile device changes from charging phase to disconnected (from power).
  • Battery run time.

Among other things; although one might think that this API isn't very useful when creating a web application for devices compared to others such as:

It is important to mention that it can be useful depending on the desired purpose of the application; for example, a web application that darkens certain interface elements to adjust colors when the battery is low with the goal of turning off pixels on the screen and thus saving battery.

Attributes of the navigator.battery object

The following properties are provided by the navigator.battery object:

chargingBoolean indicating whether the mobile device is in the charging phase (true) or not (false).
chargingTimeRepresents the remaining time in seconds until the mobile device's battery is fully charged; the chargingTime attribute should be close to 0 if the battery is full or there is no battery connected, and positive infinity if the battery is discharging or the application cannot report the remaining charge time.
dischargingTime

Represents the remaining time in seconds until the mobile device's battery is fully discharged; the dischargingTime attribute takes the value of positive infinity if: 

  • The battery is charging.
  • The application cannot report the remaining discharge time (time until the battery runs out).
  • There is no battery connected to the system.
level

Through a scale of 0.0 to 1.0, the attribute establishes that: 

  • The attribute is set to 0 if the battery is depleted.
  • The attribute is set to 1.0 if the battery is at its full capacity (100%).

What the Battery API is and what it's used for in a web application

The Battery API, also known as the Battery Status API, offers real-time information about the device's battery status:

  • Charge level
  • Whether it is plugged in/charging
  • Estimated time to full charge
  • Estimated time to full discharge

It is an API designed so that web applications can automatically adjust to the user's energy status. For example: activate a power saving mode, disable heavy effects, or prioritize critical tasks.

Events of the navigator.battery object

It is possible to define a series of events:

onchargingchangeFor the charging property.
onchargingTimechangeFor the chargingTime property.
ondischargingTimechangeFor the dischargingTime property.
onlevelchangeFor the level property.

How to get the BatteryManager object

To use the API, the browser exposes the method:

const battery = await navigator.getBattery();

We can see the summary of all properties and events in the following section:

// Get the battery object according to the browser
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
// properties
battery.charging;
battery.level;
battery.dischargingTime;
// events
battery.addEventListener("chargingchange", function(e) {}, false);
battery.addEventListener("chargingtimechange", function(e) {}, false);
battery.addEventListener("dischargingtimechange", function(e) {}, false);
battery.addEventListener("levelchange", function(e) {}, false);

Differences between navigator.battery and navigator.getBattery()

When I started with this API, I used something like:

navigator.battery || navigator.webkitBattery || navigator.mozBattery;

Today that is obsolete, and the correct way is navigator.getBattery().

The first variant only works in very old browsers and you shouldn't use it in new projects.

Key BatteryManager properties explained step by step

level: know the battery level in real time

  • Returns a value between 0.0 and 1.0.
  • To display it as a percentage: battery.level * 100.

I remember the first time I used it I was surprised how quickly it updated when disconnecting the charger; ideal for triggering small visual changes.

charging: detect if the device is charging

  • true if the device is plugged in.
  • false if it is discharging.

This is perfect if you want to automatically deactivate power saving modes when the user connects their mobile device.

chargingTime and dischargingTime: how to interpret the estimated times

These values are in seconds and can be:

  • 0 → if it is fully charged
  • A positive number
  • Infinity → when the browser cannot calculate the time
    (this happened to me very often while testing on old laptops)

Battery API Events and how to react to state changes

levelchange

Fires when the battery level changes.

chargingchange

Fires when the device starts or stops charging.

chargingtimechange

When the estimated charging time varies.

dischargingtimechange

When the estimated discharge time changes.

More than once I used the levelchange event to launch a "power saving mode activated" notice, and honestly, it gave the interface a very professional touch.

Practical examples with JavaScript (includes async/await and .then)

Get the BatteryManager and display the battery level

navigator.getBattery().then(battery => { console.log("Level:", battery.level * 100 + "%"); });

Async/await version:

const battery = await navigator.getBattery(); console.log(`Battery: ${battery.level * 100}%`);

Listen for events to automatically update the interface

 function updateBatteryUI() {
   console.log("Cargando:", battery.charging);
   console.log("Nivel:", battery.level * 100 + "%");
 }
 updateBatteryUI();
 battery.addEventListener("levelchange", updateBatteryUI);
 battery.addEventListener("chargingchange", updateBatteryUI);
});

Create alerts or power saving modes when the battery is low

This example I used myself to darken parts of the UI:

navigator.getBattery().then(battery => {
 battery.addEventListener("levelchange", () => {
   if (battery.level < 0.30 && !battery.charging) {
     document.body.classList.add("ahorro-bateria");
   } else {
     document.body.classList.remove("ahorro-bateria");
   }
 });
});

Real use cases: when it makes sense to use this API

  • Adapt the design when the battery is low
    • Dark mode, remove shadows, lower simulated brightness, etc.
  • Reduce external loads, animations or images
    • For example, if the battery is below 20%. The page instantly became lighter.
  • Dynamic UI adjustment
  • Reading mode
  • Automatic saving
  • Pause non-critical tasks

Browsers that actually support it today

Support is very limited (deprecated) in many major browsers (like Firefox and Safari on iOS/macOS) due to privacy concerns:

  • Firefox: ✔ Works
  • Chrome: ✘ Removed years ago due to privacy
  • Edge: ✘ Not available
  • Safari: ✘ Never supported it

Frequently Asked Questions about the Battery API

  • Does it still work in 2025?
    • Yes, but mainly in Firefox.
  • Can I detect low battery in JavaScript?
    • Yes: battery.level < 0.20.
  • Is it secure?
    • Browsers restricted its use due to privacy, hence its deactivation in most.
  • How to get the battery level?
    • const battery = await navigator.getBattery(); battery.level.
  • Are there modern alternatives?
    • No direct ones. Today you depend on the browser.

Conclusion

The HTML5 Battery API with JavaScript is small but powerful. Although it is now limited by privacy issues, it is still a useful tool for experimental projects, user-adapting interfaces, or web applications that optimize their energy consumption.

And, from my own experience, when you play with its events and properties, it starts to open up creative ideas about what an interface can do when it knows how much battery the device has left.

See example Download source

Learn how to use the Speech Recognition API with JavaScript to do voice dictation

I agree to receive announcements of interest about this Blog.

Learn how to use the Battery Status API with JavaScript to read battery levels, detect charging, and create power-saving modes. Includes practical examples using `navigator.getBattery()` and `async/await`.

| 👤 Andrés Cruz

🇪🇸 En español