W3docs

Battery API

The Battery API in JavaScript is a useful interface that allows web developers to access and monitor the status of a device's battery.

Battery API in JavaScript: Monitoring Device Battery Status

The Battery API in JavaScript is an interface that lets web pages read the status of a device's battery: how full it is, whether it is charging, and how long until it is full or empty. With this information a web application can adapt its behavior — for example, throttling background work or dimming heavy animations when the device is low on power. This article explains what the Battery API is, the data it exposes, when it is worth using, and how to read it correctly with promises and events.

Note: Because the battery level is a strong fingerprinting signal (it is a near-unique number that changes slowly), browsers have rolled the Battery API back. It has been removed from Firefox and Safari, and navigator.getBattery() is only available in Chromium-based browsers (Chrome, Edge, Opera) over a secure (HTTPS) context. Treat it as a progressive enhancement and always feature-detect before calling it — your code must work when the API is missing.

What is the Battery API?

The Battery API is exposed through a single method, navigator.getBattery(), which returns a Promise that resolves to a BatteryManager object. That object carries four read-only properties describing the current state, plus four events that fire whenever any of those values change. Because getBattery() is asynchronous, you read it with .then() or with async/await.

BatteryManager properties

PropertyTypeMeaning
chargingbooleantrue when the device is charging (or has no battery, e.g. a desktop).
levelnumberCharge level from 0 (empty) to 1 (full). Multiply by 100 for a percentage.
chargingTimenumberSeconds until fully charged. 0 if already full, Infinity if not charging.
dischargingTimenumberSeconds until empty. Infinity if charging or the time is unknown.

BatteryManager events

EventFires when
chargingchangeThe device starts or stops charging (charging flips).
levelchangeThe level value changes.
chargingtimechangeThe estimated chargingTime changes.
dischargingtimechangeThe estimated dischargingTime changes.

Each event is a plain DOM event, so you subscribe with addEventListener on the BatteryManager.

Benefits of the Battery API

  • User Experience Enhancement: By accessing battery status information, web applications can adapt their behavior to conserve power when the device is running on battery or provide enhanced features when the device is plugged in and charging.
  • Energy Efficiency: Utilizing battery status information, web apps can optimize resource-intensive operations to reduce energy consumption and extend device battery life.
  • Real-Time Updates: The API provides real-time updates on battery status changes, allowing web apps to respond immediately to changes such as unplugging the device or low battery levels.
  • Browser Support: The Battery API is available in several modern browsers, though developers should implement feature detection to ensure compatibility across different environments.

When to Use the Battery API

Consider using the Battery API when your web application needs to:

  1. Provide Power-Aware Features: Adapt your application's features and behavior based on whether the device is running on battery power, charging, or fully charged.
  2. Conserve Battery Life: Optimize resource-intensive operations when the device is running on battery power to reduce energy consumption and prolong battery life.
  3. Display Battery Status: Show battery-related information to users, such as the current battery level or estimated time until the battery is fully charged.
  4. Trigger Actions on Battery Events: Execute specific actions when the battery status changes, such as displaying a low battery warning or pausing resource-intensive tasks.

Practical Use Cases

  1. Low Battery Alert: You can use the Battery API to trigger a low battery alert when the device's battery level drops below a certain threshold, prompting users to conserve energy or plug in their device.
  2. Energy-Efficient Animations: Web applications can adjust the intensity and frequency of animations based on the device's battery status to reduce the drain on the battery.
  3. Background Process Management: Optimize background processes, such as syncing data or sending notifications, to occur less frequently when the device is running on battery power to conserve energy.
  4. Dynamic Resource Loading: Load high-resolution images or resource-intensive content only when the device is charging or when the battery level is above a certain threshold, improving performance and energy efficiency.

Feature Detection

Never assume getBattery() exists. Guard every call so unsupported browsers fall back gracefully instead of throwing a TypeError:

async function readBattery() {
  if (!('getBattery' in navigator)) {
    return 'Battery API not supported';
  }

  const battery = await navigator.getBattery();
  const percent = Math.round(battery.level * 100);
  return `${percent}% — ${battery.charging ? 'charging' : 'on battery'}`;
}

'getBattery' in navigator is the canonical check: it is true only where the API is present. The async/await form reads the resolved BatteryManager exactly like the .then() form but flows top-to-bottom.

Basic Example: Monitoring Battery Status

The example below reads the battery once and then keeps the on-screen text in sync by listening for the relevant events. Note the toHours helper — chargingTime and dischargingTime are reported in seconds, so dividing by 3600 turns them into readable hours. Both values can be Infinity, so we handle that case explicitly.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Battery Time Estimation</title>
</head>
<body>
    <h1>Battery Time Estimation</h1>
    <div>Time Remaining: <span id="timeRemaining">Calculating...</span></div>

    <script>
    if ('getBattery' in navigator) {
        navigator.getBattery().then(function(battery) {
            const output = document.getElementById('timeRemaining');

            function toHours(seconds) {
                return (seconds / 3600).toFixed(1);
            }

            function updateTimeRemaining() {
                if (battery.charging) {
                    if (battery.chargingTime === Infinity) {
                        output.textContent = 'Plugged in, charge time unknown';
                    } else {
                        output.textContent = `Charging, ${toHours(battery.chargingTime)} hours until full`;
                    }
                } else if (battery.dischargingTime === Infinity) {
                    output.textContent = 'On battery, time remaining unknown';
                } else {
                    output.textContent = `On battery, ${toHours(battery.dischargingTime)} hours remaining`;
                }
            }

            updateTimeRemaining();

            battery.addEventListener('chargingchange', updateTimeRemaining);
            battery.addEventListener('levelchange', updateTimeRemaining);
            battery.addEventListener('chargingtimechange', updateTimeRemaining);
            battery.addEventListener('dischargingtimechange', updateTimeRemaining);
        }).catch(function(error) {
            document.getElementById('timeRemaining').textContent = 'Battery API not available or access denied.';
            console.error('Battery API error:', error);
        });
    } else {
        document.getElementById('timeRemaining').textContent = 'Battery API not supported in this browser.';
    }
    </script>
</body>
</html>

How It Works:

  • Time Estimation: The script checks whether the battery is charging or discharging and displays an estimated time until the battery is fully charged or depleted.
  • Event Listeners: It updates the display in real-time as the battery status changes.

This example helps to illustrate how the Battery API can provide detailed insights into battery usage, including time estimates, which can be particularly useful for mobile devices and laptops in managing power consumption and planning usage.

Reacting to a Low Battery

A common pattern is to switch the page into a "power-saver" mode once the charge drops below a threshold while running on battery. Listen for levelchange and chargingchange together so you re-evaluate the mode on either signal:

async function watchPowerSaver(onChange) {
  if (!('getBattery' in navigator)) return;

  const battery = await navigator.getBattery();

  function evaluate() {
    // Save power only when on battery and below 20%.
    const lowPower = !battery.charging && battery.level < 0.2;
    onChange(lowPower);
  }

  evaluate();
  battery.addEventListener('levelchange', evaluate);
  battery.addEventListener('chargingchange', evaluate);
}

// Usage: pause heavy animations when low on power.
watchPowerSaver((lowPower) => {
  document.body.classList.toggle('reduce-motion', lowPower);
});

This is far cheaper than polling on a timer: the callback runs only when the battery state actually changes.

Common Gotchas

  • It may never resolve to useful data. On a desktop with no battery, charging is true, level is 1, and both time properties are 0 or Infinity. Don't treat the API as a reliable signal of "on a laptop."
  • Infinity is normal. chargingTime is Infinity whenever the device isn't charging, and dischargingTime is Infinity whenever the time can't be estimated. Always branch on it before formatting.
  • Estimates are coarse and clamped. To reduce fingerprinting, browsers round level and the time values, so don't build precise countdowns on top of them.
  • Secure context required. getBattery() is only available on HTTPS pages (and localhost). On plain HTTP it is undefined, which your feature check catches.
  • Remove listeners you no longer need. If you attach listeners inside a component, detach them with removeEventListener on teardown to avoid leaks.

Conclusion

The Battery API in JavaScript provides web developers with a tool to access and respond to the battery status of user devices. By utilizing this API, web applications can enhance user experience, conserve battery life, and optimize energy efficiency. While browser support varies due to privacy considerations, the Battery API lets you create power-aware experiences where supported — as long as you feature-detect, handle Infinity time values, and treat the data as a best-effort hint rather than a guarantee.

Practice

Practice
What can the Battery API in JavaScript provide information about?
What can the Battery API in JavaScript provide information about?
Was this page helpful?