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:-
console.log("Battery charging? "
+ (battery.charging ? "Yes" : "No"));
console.log("Battery level: "
+ battery.level * 100 + "%");
console.log("Battery charging time: "
+ battery.chargingTime + " seconds");
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.
Also published on Medium.