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
- Get the Current URL
- Get URL Query Parameters
- How to Smooth Scroll to an HTML Element
- Sort a Set
- New, Immutable Array Methods
- Detect Network Error
- Create Array from AsyncIterable
- Using the new Array Grouping Methods
- Test for LocalStorage Support
- Get Battery Status
- Detect If a Device Battery Is Charging (Coming soon)
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!