Techumber
Home Blog Work

How to find your device battery status using JavaScript

Published on November 23, 2016

There are few new JavaScript API’s available to deal with native devices hardware. These API’s are very useful when we develop the progressive web apps.

One such API is HTML5’s Battery-API. By using this we can determine the current battery status of the device.

You can read the complete spec here

Battery API is relatively new. It may not support in all browsers across all devices. First, we need to check if it is available in the current browser or not.

if ('getBattery' in navigator) {
  // do something with battery API
}

Battery API uses new Promises API for everything. So,

var $battery = navigator.getBattery();

$battery.then(function(r) {
  console.log(r);
});

Here, navigator.getBattery() returns a promises.

The result of the code would be


BatteryManager {
  charging: true,
  chargingTime: 0,
  dischargingTime: Infinity
  level: 0.89
  onchargingchange: null
  onchargingtimechange: null
  ondischargingtimechange: null
  onlevelchange: null
}

Here level: 0.89 that means it has 89% battery remaining.

Let’s create a simple web page which shows battery current status in percent and check if the power cable is connected or not.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Battery API Example</title>
  </head>
  <body>
    <div>
      <div>Battery Leval: <span id="leval"></span></div>
      <div>Is Chargeing : <span id="charging"></span></div>
    </div>

    <script>
      (function() {
        // check if battery API is available
        if ('getBattery' in navigator) {
          var $battery = navigator.getBattery();

          $battery.then(function(btry) {
            document.querySelector('#leval').textContent = btry.level * 100 + '%';
            document.querySelector('#charging').textContent = btry.charging ? 'Yes' : 'No';
          });
        }
      })();
    </script>
  </body>
</html>

Now, When you connect your device to power Is Chargin will show yes. Also in #level div it will show the current battery status in percent.

We have the following event on the battery API. onchargingchange, onlevelchange and ondischargingtimechange.

Let’s say we want to warn the user if the battery is less than 10%.

Let’s extend the previous code.

var $battery = navigator.getBattery();

$battery.then(function(btry) {
  //........
  btry.onlevelchange = function() {
    if (btry.level < 0.1) {
      alert('Your battery is too Low!!!');
    }
  };
});

Now when you load the web page it checks the battery level and alerts the user if the battery is less than 10%.