Recipe 14.1

Reading the Battery Status

navigator.getBattery returns a Promise which resolves to an object containing information about the battery status. You can also subscribe to events to be notified about changes in the battery charge status.

This example shows the current charging status and battery level of your device, if available.

Demo

Battery Status

Your browser does not support the Battery Status API.

Code

JavaScript
if ('getBattery' in navigator) {
  navigator.getBattery().then(battery => {
    const batteryIcon = document.querySelector('#battery-icon');
    if (battery.charging) {
      batteryIcon.classList.add('bi-battery-charging');
    } else {
      batteryIcon.classList.add('bi-battery-full');
    }

    document.querySelector('#battery-level').textContent = `${battery.level * 100}%`;
    document.querySelector('#battery-level-item').textContent = `Battery level: ${battery.level * 100}%`;
    document.querySelector('#battery-charging-item').textContent = `Charging: ${battery.charging}`;

    battery.addEventListener('chargingchange', () => {
      batteryIcon.classList.toggle('bi-battery-charging', battery.charging);
      batteryIcon.classList.toggle('bi-battery-full', !battery.charging);
      document.querySelector('#battery-charging-item').textContent = `Charging: ${battery.charging}`;
    });

    battery.addEventListener('levelchange', () => {
      document.querySelector('#battery-level').textContent = `${battery.level * 100}%`;
    })
  });
} else {
  document.querySelector('#not-supported').classList.remove('d-none');
}
HTML
<div id="demo-app">
  <h3>Battery Status</h3>
  <div class="d-flex align-items-center">
    <i class="fs-1 me-2" id="battery-icon" class="bi"></i>
    <div id="battery-level"></div>
  </div>
  <ul>
    <li id="battery-level-item"></li>
    <li id="battery-charging-item"></li>
  </ul>
</div>

<div id="not-supported" class="d-none">
  Your browser does not support the Battery Status API.
</div>
Web API Cookbook
Joe Attardi