Today I Learned - Rocky Kev

TIL about the battery status API

POSTED ON:

TAGS:

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:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.