David Jones

Battery api

We can now get the battery status of the device that is viewing your website.

At the time of writing this blog it is only firefox desktop and mobile versions that support the battery API. You can expect to see the battery API available on other browsers in the near future.

So lets take a run through of some the basic features so we can make ourself a little function that displays an alert when the battery level goes beneath 10%.

First we need to make sure the users browser supports the battery before we attempt to use the API.

var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery;

if( battery ) {
//Do stuff if the battery API exists
}

Here we are checking if the battery object is available. Some browsers will have different prefixes so we will need to check each one. It will be set to variable so we then need to check that and if it passes we can then start looking at the battery levels.

For this simple function we need to check the current level of the battery when it changes so we need to use the level change status event.

battery.onlevelchange = function() {
//Check stuff when the battery level changes
}

Now we can check the current battery level.

var level = Math.floor( battery.level * 100 );

As well as the time the remain battery will give us. It returns the value in seconds so we will need to convert it ourselves.

var time_left = battery.dischargingTime / 60; //In minutes

So now lets display a alert to the user if the battery remaining is less than 10%.

if( level < 10 ) {
     alert( 'Your battery is running low. You only have ' + time_left + ' minutes left.' );
}

There is a lot more to the battery API and you can use it to run fewer features when you battery is at a low level or like we have just demonstrated alert the user so they can take action on a low battery.

For more information be sure to check the documentation.