Introduction to the Javascript Battery API

Without knowing the battery status of a device, a web developer must design the web application with an assumption of sufficient battery level for the task at hand. This means the battery of a device may exhaust faster than desired because web developers are unable to make decisions based on the battery status.

¿Do you care about the tasks about the battery when programming a web app ?

Please share your answer with the community in the comment box.

There are many cases in which this API could be useful :

  • This can be used to adjust your app's resource usage to reduce battery drain when the battery is low.
  • Save changes of something like an editor before the battery runs out in order to prevent data loss.
  • Create a cool widget in your app to show the battery status to your user.

Let's get started !

Checking for availability

To check if the battery API is available in your Browser use any of the following if statements :

if(typeof(navigator.getBattery) != "undefined"){
    console.log("Available");
}

// Or

if("getBattery" in navigator){
    console.log("Available");
}

Although the Battery API is not relatively new, 

Navigator.getBattery Compatibility API

Source : Can I use.

And nope, there's no available polyfill for this API, how do you polyfill something that requires access to the hardware?.

All you need to know about the API

To use the Battery API, use the following snippet :

navigator.getBattery().then(function(battery){
    console.log(battery.charging); // Boolean
    console.log(battery.chargingTime); // Infinity
    console.log(battery.dischargingTime); // Infinity
    console.log(battery.level ); // Float (0 to 1)
});

The battery API return a native Promise, which means this is an asynchronous method (read more about the javascript promises here).

The Battery API, provides information about the system's battery charge level and lets you be notified by events that are sent wheter the battery level or charging status change.

  • The charging attribute represents the charging state of the system's battery.
  • The chargingTime attribute represents the time remaining in seconds until the system's battery is fully charged.
  • The dischargingTime attribute represents the time remaining in seconds until the system's battery is completely discharged and the system is about to be suspended
  • The level attribute represents the level of the system's battery.

The API provide in addition 4 events to check when a property changes.

event handler event handler event type
onchargingchange chargingchange
onchargingtimechange chargingtimechange
ondischargingtimechange dischargingtimechange
onlevelchange levelchange

You can add listeners easily using :

navigator.getBattery().then(function(battery){
    battery.onlevelchange = function(){
        alert("The battery level has changed");  
    };
    
    // Or
    
    battery.addEventListener("levelchange",function(){
        alert("The battery level has changed");  
    },false);
});

How to check if you're using a Desktop computer

Although it doesn't make sense, the battery API is available in a Desktop computer too and there's no way to know if the user is using a laptop or a desktop computer, however you can make a "supposition" with the following snippet.

You can check if you're using a Desktop computer checking if the dischargingTime property is finite or not and checking if the charging property is set to true.

navigator.getBattery().then(function(battery){
    var desktopOrLaptopConnectedInfo = function(_battery){
        if((_battery.charging === true) && !isFinite(_battery.dischargingTime)){
            console.log("Desktop detected");
        }
        // or
        
        //if((data.charging === true) && (data.dischargingTime == Infinity)){
        //    console.log("Desktop detected");
        //}
    };
    
    
    // And you may want to check when again if is a laptop and the
    // charging property changes
    battery.addEventListener('chargingchange', function(){
        desktopOrLaptopConnectedInfo(battery);
    });
});

Pitifully, if the user uses a laptop and disconnects the charger, then the supposition will fail and you'll need to add the chargingchange listener to check again.

Note: you can check in the if statement for the level property to be equal to 1 (which indicates that the "battery" is fullcharged) to increase accuracy as the properties chargingTime and dischargingTime are always equal to Infinity.

This could interest you

Become a more social person