JavaScript — Get Battery Status

Browsers become powerful when it comes to interacting with the user’s system. For example, the Battery API allows you to retrieve information about the system’s battery charge level. You may check whether a device is charging and has enough energy.

This tutorial shows you how to retrieve the system charging status using the browser Battery API.

JavaScript Series Overview

Access the Battery API

Browsers provide the Battery API via the global navigator.getBattery() object. This method returns a Promise resolving with a BatteryManager instance. The battery manager exposes properties to get the battery status:

navigator.getBattery().then(battery => {  
  //
})
In some browsers, the `BatteryManager` may be only available when requesting a website via HTTPS. For example, since Chrome 103, the Battery Status API is only exposed in secure contexts.  

Get the Charging Level

The battery manager instance has a battery.level property providing the system charging level. The level property is read-only and a number representing the charging level with a value between 0.0 and 1.0:

navigator.getBattery().then(battery => {  
  console.log(battery.level)
  // 0.76
})

You need to adjust the retrieved battery level if you want to display a percentage output. Also, you should ensure that the battery level has a correct rounding. The value “should” be in the correct output rounding, but as always: make sure you’re not displaying numbers with lots of decimal places.

In the next tutorial, we’ll detect if a device’s battery is charging. The battery API provides a battery.charging property telling you whether a battery is currently charging, but that value could be misleading if your system is consuming more power than it receives. Stay tuned!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.