The web keeps growing and getting more sophisticated. As a result, more support is being poured into the web, giving it the ability to do things native to the operating system.
In this shot, we look into the Battery API.
The Battery API provides information on the charge level of the battery in our system, as well as events to monitor our battery level status.
The getBattery()
method in the navigator
object returns the battery info and the events we can use to monitor the battery charge level.
The navigator.getBattery
returns a Promise. The Promise, when resolved, gets a battery option.
navigator.getBattery().then(battery => {
// ...
})
// OR using async/await
await navigator.getBattery();
The battery
arg is an object that contains the battery options.
The battery object has the following properties:
level
: This indicates the current charge level of the battery.
charging
: A Boolean value that indicates whether the battery is currently charging or not.
levelchange
: An event listener that is called when the charge level of the battery is incremented or decremented i.e changes.
chargingchange
: An event listener that is called when the charging status changes. That is, when the device is plugged into electricity or plugged out of it.
navigator.getBattery().then(battery => {
log("Battery Level: " + battery.level)
log("Battery Charging Status: " + battery.charging)
})
// OR
const battery = await navigator.getBattery();
log("Battery Level: " + battery.level);
log("Battery Charging Status: " + battery.charging)
This will paint the battery level and the charging status of our battery.
Full code
Find the full code of this Battery API with examples here and see a live playground here.