Native JavaScript for Battery Status API
Battery Status API
Battery Status API is being provided by the Web Platform itself and is available across multiple browsers. Battery Status API helps you to understand the state in which the device is in. This can help you to optimize the content that is being delivered. For example, at times you don’t want some heavy animations on the screen or some video running by default. In such cases, it’s better to determine the state of the Battery of the device. There are few other use-cases where you can deliver great content by optimizing the site/app and in a device with a low battery state.
Implementation of Battery Status API
The implementation is pretty simple. We will be looking at configuring various event listeners as listed below:-
Let’s write a small program and then you can have it run online and check the way it works. The code will go as follows:-
navigator.getBattery().then(function(battery) {
function updateAllBatteryInfo(){
updateChargeInfo();
updateLevelInfo();
updateChargingInfo();
updateDischargingInfo();
}
updateAllBatteryInfo();
battery.addEventListener('chargingchange', function(){
updateChargeInfo();
});
function updateChargeInfo(){
console.log("Battery charging? "
+ (battery.charging ? "Yes" : "No"));
}
battery.addEventListener('levelchange', function(){
updateLevelInfo();
});
function updateLevelInfo(){
console.log("Battery level: "
+ battery.level * 100 + "%");
}
battery.addEventListener('chargingtimechange', function(){
updateChargingInfo();
});
function updateChargingInfo(){
console.log("Battery charging time: "
+ battery.chargingTime + " seconds");
}
battery.addEventListener('dischargingtimechange', function(){
updateDischargingInfo();
});
function updateDischargingInfo(){
console.log("Battery discharging time: "
+ battery.dischargingTime + " seconds");
}
});
You can see it in action in the below-mentioned GIF. Or just check out the JSFiddle Sample.
Battery Status API
You can as well check out the entire sample at the JSFiddle embedded below. Have a look at how navigator object has access to getBattery() function which gets us the battery status altogether. You can utilize this to provide great User Experience through this. Let us know what are your views about the Battery Status API. You can alternatively implement this in your JAvaScript application and make it a part of your code and let us know how did you optimize your user’s experience.
Originally published at The Web Juice.