Get battery level JavaScript
Asked Answered
L

5

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.

Latifundium answered 4/11, 2015 at 11:53 Comment(4)
Note that your link to JSFiddle leads to the home page, not a specific fiddle demonstrating the problem.Devaughn
##Chrome 60:## Input > window.navigator.battery ---------- Output< undefinedPaleoclimatology
As it it deprecated, I will mention it in the top of this issue, thank you.Latifundium
In one line: navigator.getBattery().then(battery => console.log(battery.level));Immunity
S
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.

Spoilage answered 4/11, 2015 at 11:56 Comment(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.Latifundium
L
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);
});
Latifundium answered 4/11, 2015 at 12:6 Comment(0)
F
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>
Firkin answered 16/1, 2021 at 14:11 Comment(0)
K
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

Karolkarola answered 17/11, 2016 at 22:28 Comment(5)
How does this answer differ from @Zeratops' answer?Devaughn
This is a REALTIME output because of using event handlers @MikeMcCaughanKarolkarola
Do you have any JSFiddle to test it @AbdennourTOUMI ?Latifundium
Ahleen @Anwar! a Jsfiddle link has been added to the answerKarolkarola
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...Latifundium
T
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.

Towage answered 29/8, 2018 at 7:44 Comment(1)
Thank you @Temkit, gonna add this critical piece of information on my own answer.Latifundium

© 2022 - 2024 — McMap. All rights reserved.