TIL about the battery status API
POSTED ON:
NOTE: This only works in Chrome/Chromium (like Edge)
MDN
Check out What can the web do today for more compatibility.
Do you want to know all about the battery of your laptop, PC or, devices? This API helps in knowing all the information like, the battery is charging or not, how much charge is left and also the handlers to handle the charge related state changes.
navigator.getBattery().then(function (battery) {
// handle the charging change event
battery.addEventListener("chargingchange", function () {
console.log("Battery charging? " + (battery.charging ? "Yes" : "No"));
});
// handle charge level change
battery.addEventListener("levelchange", function () {
console.log("Battery level: " + battery.level * 100 + "%");
});
// handle charging time change
battery.addEventListener("chargingtimechange", function () {
console.log( "Battery charging time: " + battery.chargingTime + " seconds");
});
// handle discharging time change
battery.addEventListener("dischargingtimechange", function () {
console.log("Battery discharging time: " + battery.dischargingTime + " seconds");
});
});
via Tapas Adhikary's 10 lesser-known Web APIs you may want to use
Related TILs
Tagged: mdn