In this tutorial I am going to show you how easily you can check battery status of system using javascript battery API . Using the battery API various information about the system battery can be extracted , thus increasing the user experience also in case user needs urgent charging .
Getting battery Information
The battery API is not working in all browser , so first of all before getting the battery status we need to check that if browser supports the battery API or not .
Checking API working in browser
Now to check the working of API in browser we need to use getBattery method on navigator API , as shown in the example below .
if(navigator.getBattery){
// if battery API is working
}
else{
// if battery API is not working
}
Check battery status
If the battery API is working then we can check the battery percentage with getBattery()
API , this API returns a promise .
navigator.getBattery()
.then(function(battery) {
// Get current battery level .
var batteryLevel = battery.level * 100;
console.log(batteryLevel);
})
.catch(function(e) {
console.error(e);
});
The battery
object has the following properties we can use to extract more information about sytem battery .
- battery.level : to check the battery level
- battery.charging : to check if the battery is currently charging or not (true/false)
- battery.chargingTime : to check the time remaining in full charge of battery
- battery.dischargingTime : to check the time remaining in battery dead .
Now to detect changes in all these properties at real time javascript provide us some event listeners , as shown below .
- battery.onlevelchange : to detect change in battery level
- battery.onchargingchange : to detect change in power plug in/out of battery
- battery.onchargingtimechange : to detect change in battery level
- battery.onlevelchange : to detect change in battery level
In the below example as soon as the battery level goes below 15% an alert will popup recommending connecting system to charger .
if(navigator.getBattery){
// if battery API is working
navigator.getBattery()
.then(function(battery) {
battery.onlevelchange = function() {
if(battery.level<0.15 && !battery.charging) {
alert("Connect to charger");
}
}
});
}
That’s how you can get alot of information with javascript getBattery()
API .
So that’s all for this aritcle guys . You can
Follow me on Linkedin : Anand Raj
Follow our Linkedin page : Be Practical
Join Our Telegram community over here
Checkout our latest course on udemy


Chat Application with Javascript , Jquery and Firebase
Rating : 4.8
2.5 Total Hours | 27 Lectures | Intermediate
Next Article : Easiest way to connect database with javascript : 3 simple steps
Thanks for reading ✌