Yes, you heard me right, the Battery API! As the web expands, so does the number of devices we expect to use our programs. This API can be particularly useful for protecting our mobile users and their precious battery life! So before we look at the API lets think of some reasons why we might need such a thing:
So let’s take a look at how you might use it.
A few things to note in the above example:
getBatteryis not available in all browsers. Make sure you perform a check before attempting to use it!
Promisewhich resolves with the
onchangefunction is called, you must re-inspect the original
BatteryManagerobject that was provided by the promise. It will be modified and contain the new battery information.
onchangefunction is called it receives one argument,
event, which helpfully contains
event.typethat tells us which battery event happened. This allows you to reuse a single event handler!
Now that we see how to get the data, let’s take a look at how we can use it!
In this example we will watch for the battery to get low, and show an alert when it’s below a certain level.
The battery properties we are inspecting:
dischargeTimeis the amount of time until the battery is empty, in seconds. Its value will be
infinityif the device is plugged in to a power source.
levelis a percentage. So
You can customize these to fit your needs. In a highly time-sensitive environment you may want to let them know earlier than 20% or 20 minutes.
A final note: Most devices will warn users when the battery is low, so you likely won’t need to add the example warning message to your application. Instead, you could limit your processes and display a message that processing is limited until the battery has been charged. Remember, this API is just another resource that allows you to solve problems for your users.
Hi, I’m Justin Fuller. I’m so glad you read my post! I need to let you know that everything I’ve written here is my own opinion and is not intended to represent my employer in any way. All code samples are my own, and are completely unrelated to Bank Of America’s code.
Hacker Noon is how hackers start their afternoons. We’re a part of the @AMIfamily. We are now accepting submissions and happy to discuss advertising &sponsorship opportunities.
To learn more, read our about page, like/message us on Facebook, or simply, tweet/DM @HackerNoon.
If you enjoyed this story, we recommend reading our latest tech stories and trending tech stories. Until next time, don’t take the realities of the world for granted!