If you like this, please consider buying me a coffee

Check your battery status


Did you know websites can monitor your device's battery?!

They can see when a device is or isn't charging, what the current battery level is, as well as how long it will take for the the battery to die or finish charging.
100%

How to achieve this in javascript


This requires the navigator.getBattery() method. Not all browsers support this, so you need to check. This method returns a Promise, which resolves with a BatteryManager object, which has the following attributes:

levelA number 0-1 e.g. 0.5 is 50% battery
chargingA boolean of whether or not device is plugged in
chargingTimeThe number of seconds until the device is fully charged
dischargingTimeThe number of seconds until the battery is empty

The BatteryManager also has an addEventListener() method, which allows you to detect when any of the above attributes change.

The following code snippet prints battery information and changes to the console:

// Not all browsers have this feature, so check it's available if(navigator.getBattery){ navigator.getBattery().then(function gotBattery(battery) { let hasBattery = false; // Define a generic function for handling all battery changes const onChange = function onChange(event) { // We have battery if previously detected one, or a battery // event occurred, or battery is not charging/depleted hasBattery = hasBattery || !!event || !battery.charging || battery.level !== 1; console.log([ 'hasBattery: ' + hasBattery, 'level: ' + battery.level, 'charging: ' + battery.charging, 'chargingTime: ' + battery.chargingTime, 'dischargingTime: ' + battery.dischargingTime, ].join('\n')); }; // Populate with initial data onChange(); // Register event listeners for any changes battery.addEventListener('chargingchange', onChange); battery.addEventListener('chargingtimechange', onChange); battery.addEventListener('dischargingtimechange', onChange); battery.addEventListener('levelchange', onChange); }); }else{ console.log('This browser does not support navigator.getBattery()'); }

For more information, check out the MDN page.
Copyright © 2024 Jools Chadwick