Exploring the Battery Status API

A Frontend Developer’s Guide

Amresh Kumar
5 min readJun 2, 2024

What is the Battery Status API?

The Battery Status API is a web API that provides information about the system’s battery status. It allows web developers to monitor battery level, charging status, charging time, and discharging time. This information can be used to optimize web applications based on the device’s power availability.

Use Cases

  1. Power Optimization: Adjust the behavior of web applications to conserve battery life when the battery is low.
  2. User Notifications: Inform users when their device’s battery is critically low or when it is charging.
  3. Resource Management: Disable or reduce the frequency of power-intensive operations when the battery is low.
  4. User Experience: Enhance user experience by providing feedback based on the battery status, such as changing themes or disabling animations.

Advantages

  • User Awareness: Allows developers to inform users about battery status and suggest actions to save battery life.
  • Power Management: Helps in managing the app’s resource usage based on battery levels.
  • Improved User Experience: Provides a better user experience by adapting to the battery status.

Disadvantages

  • Browser Support: Limited support across different browsers, especially older versions.
  • Privacy Concerns: Continuous monitoring of battery status could raise privacy concerns among users.

Getting Battery Information

navigator.getBattery() is a promise-based method that retrieves information about the battery status of the user’s device. Upon resolution, it returns a BatteryManager object, which encapsulates various properties and event handlers to monitor and interact with the battery.

Here’s an overview of the properties and events provided by the BatteryManager object:

Properties:

  1. charging: Indicates whether the device is currently charging or not. It returns a boolean value (true if charging, false otherwise).
  2. chargingTime: Represents the time, in seconds, until the battery is fully charged. If the device is not charging, it returns Infinity.
  3. dischargingTime: Indicates the estimated time, in seconds, until the battery is fully discharged when not connected to a power source. If the device is charging, it returns Infinity.
  4. level: Represents the current battery level as a value between 0 and 1, where 0 indicates a fully discharged battery, and 1 indicates a fully charged battery.

Events:

  1. chargingchange: Fired when the charging state of the device changes (i.e., when the device starts or stops charging).
  2. chargingtimechange: Triggered when there’s a change in the estimated time until the battery is fully charged.
  3. dischargingtimechange: Fired when there’s a change in the estimated time until the battery is fully discharged.
  4. levelchange: Fired when there’s a change in the battery level.

These events allow developers to dynamically update the UI or trigger specific actions based on changes in the battery status. For example, you can update a battery indicator icon, display the remaining charging or discharging time, or adjust power-saving settings in response to changes in the battery level or charging state.

Small Application Example

Let’s build a small web application that shows the battery level, charging status, charging time, and discharging time. The application will change the battery color based on the level and add a green glow when charging.

Adding HTML

<!DOCTYPE html>
<html>
<body>
<div id="battery">
<div id="battery-level"></div>
</div>
<p id="battery-status"></p>
<p id="charging-time"></p>
<p id="discharging-time"></p>
</body>
</html>

The HTML contains a div element to represent the battery and p elements to display the battery status, charging time, and discharging time.

Adding CSS

  <style>
p{
text-align: center;
}

/* shape of the battery */
#battery {
width: 100px;
height: 50px;
border: 2px solid #000;
position: relative;
margin: 20px auto;
border-radius: 8px;
}

/* tip of the battery */
#battery:before {
content: "";
position: absolute;
top: 15px;
right: -10px;
width: 10px;
height: 20px;
background: #000;
}

#battery-level {
height: 100%;
transition: width 0.5s;
position: relative;
border-radius: 6px;
}

.red {
background: red;
}

.green {
background: green;
}

.blue {
background: blue;
}

/* when battery is charging, we show glowing green box-shadow*/
.charging {
animation: blink 1s infinite;
}

@keyframes blink {
0% { box-shadow: 0 0 10px green; }
50% { box-shadow: 0 0 20px green; }
100% { box-shadow: 0 0 10px green; }
}

/* Thunder sign inside battery */
.charging::after {
content: '⚡';
color: rgb(4, 94, 4);
font-size: 20px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>

The CSS styles the battery and changes its color based on the battery level. It also adds a green glow when the battery is charging.

Adding Javascript


navigator.getBattery().then(function(battery) {
function updateAllBatteryInfo() {
updateLevelInfo();
updateChargingInfo();
updateChargingTimeInfo();
updateDischargingTimeInfo();
}

// runs everytime user connects or disconnects charger
battery.addEventListener('chargingchange', function() {
updateChargingInfo();
});

// runs every time battery level changes, eg changes to 36% from 35%
battery.addEventListener('levelchange', function() {
updateLevelInfo();
});

// runs everytime time required to charge phone is changes
battery.addEventListener('chargingtimechange', function() {
updateChargingTimeInfo();
});

// runs everytime time required for the phone to be dead changes
battery.addEventListener('dischargingtimechange', function() {
updateDischargingTimeInfo();
});

function updateLevelInfo() {
const batteryLevel = battery.level * 100;
const batteryLevelDiv = document.getElementById('battery-level');
batteryLevelDiv.style.width = batteryLevel + '%';

if (batteryLevel <= 10) {
batteryLevelDiv.className = 'red';
} else if (batteryLevel <= 20) {
batteryLevelDiv.className = 'green';
} else {
batteryLevelDiv.className = 'blue';
}

document.getElementById('battery-status').textContent = 'Battery Level: ' + batteryLevel + '%';
}

function updateChargingInfo() {
const batteryDiv = document.getElementById('battery');
if (battery.charging) {
batteryDiv.classList.add('charging');
document.getElementById('battery-status').textContent += ' (Charging)';
} else {
batteryDiv.classList.remove('charging');
}
}

function updateChargingTimeInfo() {
document.getElementById('charging-time').textContent = 'Charging Time: ' + battery.chargingTime + ' seconds';
}

function updateDischargingTimeInfo() {
document.getElementById('discharging-time').textContent = 'Discharging Time: ' + battery.dischargingTime + ' seconds';
}

updateAllBatteryInfo();
});

The JavaScript code uses the Battery Status API to fetch battery information and update the UI accordingly.

  • updateLevelInfo: Updates the battery level and changes its color based on the level.
  • updateChargingInfo: Adds a green glow and updates the status when the battery is charging.
  • updateChargingTimeInfo: Displays the charging time.
  • updateDischargingTimeInfo: Displays the discharging time.
Preview of the application made using battery api

This simple application demonstrates how to use the Battery Status API to monitor battery information and adjust the UI based on the battery status.

Refrences

Congratulations on completing this article, which is part of my series, Top Web APIs Every Frontend Developer Should Know. If you’re eager to discover more about other essential APIs, make sure to check out the rest of the series. Each article dives deep into a different set of APIs, providing valuable insights and practical examples to help you level up your frontend development skills.

If you found this article helpful, don’t forget to clap for it! 👏 It helps me know what content you enjoy and want to see more of.

Also, feel free to connect with me on LinkedIn to stay updated with my latest articles and insights into software development. Let’s grow and learn together!

--

--

Amresh Kumar

Software Engineer with 3 years of experience in building full-stack application.