Tutorial: Battery API - Low charge notification

The web is pushing forward and with it its new possibilities. One of the newest achievements is the JavaScript Battery API which is already included (prefixed) in WebKit (Chrome, Safari) and Gecko (Firefox). This API provides information about the current charge level and allows you - via events - to notify the user e.g. about a low charge or allows the website to disable CPU intense operations. Some of you may ask yourself why do we need that? An important use case would be a business-critical (financial) app where you could notify the user about the low Battery charge and warn him that his data or transactions will be lost if he/she wouldn't charge their device.
Accessing the Battery object
In order to access the mentioned API you'll need to get the object:
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
Battery attributes
The object contains four readyonly attributes:
charging
- Boolean representation of the charge status. If the battery is charging, the state isn't determinable or the system has no battery it will returntrue
andfalse
if the battery is discharging.chargingTime
- Double representation of the remaining time to fully charge the battery in seconds. Returns positive infinity if the battery isn't charging or it isn't possible to get the remaining charging time.dischargingTime
- Double representation of the remaining time until the battery is discharged. Returns positive infinity if the battery is charging or it isn't possible to get the remaining discharging time or no battery is attached.level
- Double representation of the current charge status between 0.0 and 1.0.
Battery events
There are also four corresponding events:
chargingchange
- When the device is started to charge or dischargechargingtimechange
- When the device charging time changes (plugged in)dischargingtimechange
- When the device discharging time changes (unplugged)levelchange
- When the device level changes
How to inform the user
If you want to inform the user to charge their device to prevent data loss, you could do the with the following script:
// Get the object
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
// Call this function if the level of charge is under a critical value
function chargeLevelUnderCriticalValue() {
// The critical value of 5 percent
var criticalValue = 5;
// Just notify if the device isn't charged and the critical value is hit
if (!battery.charging && level <= (criticalValue / 100)) {
alert('We detected that your device has a low charge and we wanted to inform you, ' +
'that the the current operation could not be finished which could constitute data loss. ' +
'To prevent that, please charge your device. Thanks.');
}
}
// Execute function if event is fired
battery.addEventListener('levelchange', chargeLevelUnderCriticalValue);
Example
You could try the online demo.