Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
web
api
communitycreator

What is the Battery Web API?

Chidume Nnamdi

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

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.

RELATED TAGS

javascript
web
api
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring