DEV Community

Cover image for Hands on Battery Status API
Nika Dev
Nika Dev

Posted on

Hands on Battery Status API

Hi everyone, it‘s me again.

So, let‘s move on with what we’ve done before. Today, I want to write about a cool and small API — the Battery Status API.

What is the Battery Status API?

The API gives you the ability to get the battery level of your device. Besides this, you can also get information about the charging status and more detailed information about the charging and discharging time. It’s just as simple as that.


Why should I use the Battery Status API

To be honest, it’s not something that will be used by every web application. But you can use it for energy-efficient features (like reducing animations or pausing background sync) depending on the battery status.
There’s also a use case where you might want to recommend something to the user when their battery is low, such as enabling dark mode or disabling live updates.
It could also be useful if you want to use it for device diagnostics.

How can I use the Battery Status API

As with most new Web APIs, the Battery Status API can be used through an asynchronous method that returns a Promise.

const battery = await navigator.getBattery();
Enter fullscreen mode Exit fullscreen mode

This API call returns a BatteryManager object with the following properties:

  • charging (boolean)
  • chargingTime (number)
  • dischargingTime (number)
  • level (number)

Let's go quickly through the properties.

charging

This is just a boolean that indicates if the device is connected to a power source. On desktops with no battery, browsers should always return true, but in some cases, they might also return false. For typical mobile devices (laptops or smartphones), it should work as expected.

chargingTime

This is a number in seconds that tells you the estimated time your device needs to fully charge. It may take some time for your device to estimate this value. If the time isn’t yet calculated, it could return Infinity for mobile devices and may change later on. For desktop devices, it will always return Infinity.

dischargingTime

Similar to the previous one, but it tells you the estimated time until your device reaches an empty battery state.

level

This is a number that shows you the current battery level. The number is between 0 and 1 — for example, 0.5 represents 50%.

events

There are also multiple events that you can listen to:

  • chargingchange
  • levelchange
  • chargingtimechange
  • dischargingtimechange

These events will be triggered whenever one of those values changes. So nothing really special — let’s see it in action.


Everything in action

Okay, sounds easy so far. And yes, the code looks quite simple too:

async function initialize() {
   if(!navigator.getBattery) {
      console.warn("The Battery Status API is not supported in your browser.");
      return;
   }
   const battery = await navigator.getBattery();

   // event listeners
   battery.addEventListener("chargingchange", () => {
      console.log(`Battery charging? ${battery.charging ? "Yes" : "No"}`);
   });

   battery.addEventListener("levelchange", () => {
      console.log(`Battery level: ${battery.level * 100}%`);
   });

   battery.addEventListener("chargingtimechange", () => {
      console.log(`Battery charging time: ${battery.chargingTime} seconds`);
   });

   battery.addEventListener("dischargingtimechange", () => {
      console.log(`Battery discharging time: ${battery.dischargingTime} seconds`);
   });
}

// call the async function for initialization
initialize();
Enter fullscreen mode Exit fullscreen mode

For testing purposes, you can just copy this code into your browser. If you then plug in or unplug your power supply and your browser supports the API, you’ll see console updates in the DevTools.


Which Browsers support the Web Battery Status API?

I don't want to talk about it in detail, because it could be outdated. So here is the link to Web Battery Status API support.


Conclusion

As I said before, the feature is small and easy to use. So there’s no excuse not to use it when it’s useful for your application.
Unfortunately, the feature is currently (as I write this post) not supported by all major browsers, but like most new Web APIs, you can add progressive support for it.

Have you already used it in your project? Let me know in the comments if you have — or give it a try in your next one!


React usage

Reading this and want to use it inside your React application? I already created a small hook where you can use this API in the most “React-like” way possible.
Check out my post about React Hook for the Battery Status API


My sources:

Top comments (0)