Get battery level JavaScript

15,687

Solution 1

From the English version of that page:

This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

and

The battery property is deprecated and has been replaced by a Navigator.getBattery() method returning a battery Promise. Its support is still partial though.

Solution 2

WARNING

Do not use the following answer in production, as it has been deprecated since then. The spec will be reworked due to privacy and security issues, so expect to see changes and malfunctions.

ANSWER

To answer my own question, thanks to the help of the document that @Quentin provided to me, I reached my goal using BatteryManager.level function the the promise Navigator.getBattery(). The link that gives the working snippet can be found here : https://developer.mozilla.org/en-US/docs/Web/API/BatteryManager/level.

The following JSFiddle display in the console (F12) the value of the remaining battery (I could not verify the ouput in a desktop yet, so please correct me if it is not working on desktop) :

JSFiddle

JavaScript

navigator.getBattery().then(function(battery) {

    var level = battery.level;

    console.log(level);
});

Solution 3

event.target.level is the level value in the event handlers.

navigator.getBattery().then((battery) => {

    battery.ondischargingtimechange = (event) => { 
       console.warn(`Discharging : `, event.target.level) 
    };

    battery.onchargingtimechange = (event) => { 
       console.info(`Charging : `, event.target.level) ;
    };
});

Live Example at Jsfiddle

Screenshoot

Solution 4

Works, demo, and code included
I recommend the Battery API.
You can find the demo here or the code here
It's very useful and provides lots of information about the
battery. It's free to use.

(function() {
  let batterySupported = document.getElementById("battery-supported"),
    batteryLevel = document.getElementById("battery-level"),
    chargingStatus = document.getElementById("charging-status"),
    batteryCharged = document.getElementById("battery-charged"),
    batteryDischarged = document.getElementById("battery-discharged");

  let success = function(battery) {
    if (battery) {
      function setStatus() {
        console.log("Set status");
        batteryLevel.innerHTML = Math.round(battery.level * 100) + "%";
        chargingStatus.innerHTML = (battery.charging) ? "" : "not ";
        batteryCharged.innerHTML = (battery.chargingTime == "Infinity") ?         
"Infinity" : parseInt(battery.chargingTime / 60, 10);
        batteryDischarged.innerHTML = (battery.dischargingTime == "Infinity") 
? "Infinity" : parseInt(battery.dischargingTime / 60, 10);
      }

      // Set initial status
      setStatus();

      // Set events
      battery.addEventListener("levelchange", setStatus, false);
      battery.addEventListener("chargingchange", setStatus, false);
      battery.addEventListener("chargingtimechange", setStatus, false);
      battery.addEventListener("dischargingtimechange", setStatus, false);
    } else {
      throw new Error('Battery API not supported on your device/computer');
    }
  };

  let noGood = function(error) {
    batterySupported.innerHTML = error.message;
  };

  navigator.getBattery() //returns a promise
    .then(success)
    .catch(noGood);
})();
@import url('https://fonts.googleapis.com/css2? 
   family=Roboto:wght@300&display=swap');

/* General font styles */

html {
  font-family: 'Roboto', sans-serif;
  height: 100%;
}

body {
  font-family: 'Roboto', sans-serif;
}

img {
  border: none;
  vertical-align: middle;
}


/* Basic element styles */

a {
  color: #0366d6;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

html {
  color: #000;
}

body {
  padding-top: 20px;
}

body {
  margin-bottom: 30px;
}

ul {
  margin: 10px 0;
}


/* Structure */

.container {
  background: #fff;
  border-top: none;
  text-align: center;
}

#battery-supported {
  color: #f00;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Battery API</title>
</head>

<body>

  <div class="container">
    <h1>
      Battery API demo
    </h1>

    <section class="main-content">
      <p>A demo of the Battery API</p>

      <p id="battery-supported"></p>

      <p>Battery level is <b id="battery-level"></b></p>

      <p>Battery status is <b id="charging-status"></b><b>charging</b></p>

      <p>Battery will be fully charged in <b id="battery-charged"></b> 
minutes.</p>

      <p>Battery will be discharged in <b id="battery-discharged"></b> 
minutes.</p>


    </section>

        <p class="footer">All the code is available in the <a 
href="https://github.com/robnyman/robnyman.github.com/tree/master/battery">
 Battery 
repository on GitHub</a>.</p>
  </div>




</body>

</html>

Solution 5

Navigator.getBattery() is now obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time.

Share:
15,687
Anwar
Author by

Anwar

Fullstack developper @ Carlili

Updated on June 27, 2022

Comments

  • Anwar
    Anwar almost 2 years

    /!\ THE USE OF window.navigator.battery IS STRONGLY DISCOURAGED AND THIS ISSUE IS NOW NOT WORTH CHECKING THANK YOU /!\

    I want to get the battery level of the current system. Here is the output I intend to get:

    If desktop (no battery) Battery level : 100%

    If laptop Battery level : XXX% (depending the level)

    So I tried the snippet of the Mozilla Foundation over window.navigator.battery in my JSFiddle.

    The problem : Running Chrome 20+ version (currently 46), I still have an error on the console :

    Uncaught TypeError: Cannot read property 'addEventListener' of undefined

    So what I understand is the object battery instantiated with the supposed battery level is returning nothing.

    Did someone figured this out already ?

    The point of my algorithm when this snippet works is to define which action the user cannot perform regarding the remaining battery level. For example, I don't want the user to engage a heavy action that could probably lower his battery level to a critical point and make the critical action fail.