What is the Battery Status API in HTML5 ?
Introduction: The Battery Status API sometimes referred to as the Battery API provides information about the battery of the computer. It provides the remaining battery level and charging status of the battery. It also gives an estimate of the remaining time to completely charge the battery or discharge the battery if it is charging or discharging.
The Battery Status API is not an external API. It is available in the navigator.getBattery() method inside the built-in window.navigator property of the navigator object.
Get the battery object:
- Fetch the battery information of the system using the navigator.getBattery() method.
- The function used as a parameter for the then() method takes the battery object as an argument. This battery object carries all information about the battery of the system.
Now let’s understand different methods of Battery Status API.
1. battery.charging method: This method is used for getting the charging status of the battery.
- Return Value: It returns a Boolean ‘true’ if the battery is actively charging and ‘false’ if the battery is not charging.
- chargingchange event: We can detect the change in the charging status of the battery by adding event listeners to the battery object. If the ‘chargingchange‘ event occurs then the event listener function will be triggered.
2. battery.level method: This method returns the battery level as a number assuming the full battery level as 1. We have to multiply it by 100 to get the battery level in percentage.
- levelchange event: This event detects the change in battery level. We can trigger our conditions whenever the battery level changes by adding an event listener to the event ‘levelchange’.
3. battery.chargingTime method: This method returns the estimated time left to completely charge the battery in seconds. It returns ‘Infinity’ if the battery is not connected to a charger.
- chargingtimechange event: This event detects the change in this estimated time. We can add a listener to this event and update it.
4. battery.dischargingTime method: This method returns the estimated time left to completely discharge the battery in seconds. It returns ‘Infinity’ if the battery is connected to a charger.
- dischargingtimechange event: This event detects the change in this estimated time. We can add a listener to this event and update it.
Example: In this example, we have fetched the battery status using Battery Status API and shown the data on our webpage.
- With charger connected:
- Without charger:
As the charger is not connected it shows battery charging time as ‘Infinity’.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.