The more demanding our web apps become, the more power we draw from devices.
On desktop, where we can be sure that the device is plugged into the mains, that’s not a problem, but on a mobile device we need to know what the battery is doing and respond accordingly.
Browser support
At the time of writing the Battery API is only supported by Firefox (mobile and desktop). However, it doesn’t require a vendor prefix to be supported.
The reason I mention desktop is because this API can also be used with any laptop to check the battery state.
Using the Battery API
To get started, we need to first check if the API is supported. We do this like so:
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
This will test for any current or future support.
Then we run a quick if…else to check for support:
if (battery) {
// Supported
} else {
// Not Supported
}
battery.charging
The first thing we’ll normally want to check on the battery is whether the battery is currently charging. We can do this like so:
if(battery.charging) {
// Run application
} else {
// Don't run
}
If you want to, you can even let the user know how much battery level they have left:
$('element').append( battery.level * 100 + '%');
battery.level returns a value from 0 to 1, so by multiplying by 100 we get a percentage.
battery.dischargingTime
Of course, the battery level is just a number. What the user is really interested in is exactly how much time is left on their battery. We can test for this using battery.dischargingTime:
$('element').append(battery.dischargingTime);
This returns the number of seconds until the battery is exhausted. If you want that to be displayed in minutes then you should divide by 60:
$('.time').append(battery.dischargingTime/60 + ' minutes left');
If the device is charging you can also use battery.chargingTime to check how long the battery will take to reach full charge.
Battery events
We can also bind to several events to help avoid continual polling.
There are four different events that we can use:
- chargingchange: the charging state has changed
- chargingtimechange: the time until the battery reaches 100% has changed
- dischargingtimechange: the time until the battery is exhausted has changed
- levelchange: the battery level has changed.
You can test for states like so:
battery.onlevelchange = function() {
if(battery.level < 5)
alert('Critical Battery');
}
}
You can see some examples of this working here (make sure you’re viewing them in the most recent Firefox).