battery-status-using-mozilla-web-api

The battery object provides information about the system’s battery charge level. you can also listen to events it sends that provide updates about the battery’s charge status.

Without knowing the battery status of a device, a web developer must design the web application with an assumption of sufficient battery level for the task at hand. This means the battery of a device may exhaust faster than desired because web developers are unable to make decisions based on the battery status. Given knowledge of the battery status, web developers are able to craft web content and applications which are power-efficient, thereby leading to improved user experience.

var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
 
function updateBatteryStatus() {
console.log("Battery status: " + battery.level * 100 + " %");
 
if (battery.charging) {
console.log("Battery is charging");
}
}
// Device got plugged in to power, or unplugged
battery.addEventListener("chargingchange", updateBatteryStatus);
 
// Device's battery level changed
battery.addEventListener("levelchange", updateBatteryStatus);
 
// Device's charging time changed
battery.addEventListener("chargingtimechange",updateBatteryStatus);
 
// Device's discharging time changed
battery.addEventListener("dischargingtimechange",updateBatteryStatus);
updateBatteryStatus();

Demo:

Device support

The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 (Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15 / Firefox OS 1.0.1).