Anwar
Anwar

Reputation: 4246

Get battery level JavaScript

/!\ 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.

Upvotes: 7

Views: 23136

Answers (5)

Tiago Rangel
Tiago Rangel

Reputation: 1328

Edit: This is no longer working.


It's relatively easy, although using navigator.battery is not recommended because it is deprecated.

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 error = function(error) {
  batterySupported.innerHTML = error.message;
};

navigator.getBattery() //returns a promise
  .then(success)
  .catch(error);
<h1>
  Battery API demo
</h1>

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

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

<p>Battery status: <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>

Upvotes: 4

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93163

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

Upvotes: 3

Anwar
Anwar

Reputation: 4246

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);
});

Upvotes: 7

Sid Ali
Sid Ali

Reputation: 1857

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.

Upvotes: 3

Quentin
Quentin

Reputation: 943099

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.

Upvotes: 9

Related Questions