7

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

4
  • 3
    Note that your link to JSFiddle leads to the home page, not a specific fiddle demonstrating the problem. Commented Nov 17, 2016 at 22:35
  • ##Chrome 60:## Input > window.navigator.battery ---------- Output< undefined
    – undefined
    Commented Aug 23, 2017 at 9:03
  • As it it deprecated, I will mention it in the top of this issue, thank you.
    – Anwar
    Commented Oct 5, 2017 at 15:36
  • 1
    In one line: navigator.getBattery().then(battery => console.log(battery.level));
    – Basj
    Commented Jun 5, 2020 at 12:05

5 Answers 5

9

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.

1
  • I just figured out that the French documentation is not up to date because I switched the URL to en and I actually saw the depecrated message error.
    – Anwar
    Commented Nov 4, 2015 at 11:59
7

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

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>

3

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.

1
  • Thank you @Temkit, gonna add this critical piece of information on my own answer.
    – Anwar
    Commented Aug 29, 2018 at 7:45
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

5
  • How does this answer differ from @Zeratops' answer? Commented Nov 17, 2016 at 22:36
  • 1
    This is a REALTIME output because of using event handlers @MikeMcCaughan Commented Nov 17, 2016 at 22:44
  • Do you have any JSFiddle to test it @AbdennourTOUMI ?
    – Anwar
    Commented Nov 18, 2016 at 9:20
  • 1
    Ahleen @Anwar! a Jsfiddle link has been added to the answer Commented Jan 11, 2020 at 5:57
  • Thank you for having updated your answer! On my Huawei P20, the displayed charging time did not changed (even if I charge my phone and hold the screen open while the charge is going up). Maybe an implementation issue with the stock Android browser. Gotta try it on Android Chrome. Anyway, thank you for your input, this battery API is hard to tame I guess...
    – Anwar
    Commented Jan 11, 2020 at 9:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.