1

I made a program that would list the battery level and charging into a div. My code is below. For some reason, when I run it, it tells me that navigator.getBattery is not a function. How can I fix this?

function batttick() {
  navigator.getBattery().then( a=>{
    let m = ""
    let c = ""
    m = battery.level * 100 + "%"
  
    if(a.charging) {
      m+=" ⚡";
      c = "green";
    }
    console.log(c, m);
    document.getElementById("batt").innerHTML = m;
    document.getElementById("batt").style.color = c;
    })
} 
batttick()
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
lolBOT V9.17
  • 141
  • 10

2 Answers2

2

The error that you are getting is not coming up when running on Google Chrome (version 100).

It looks like a few browsers don't support navigator.getBattery(). See the browser compatibility on MDN, or see the table below.

Browser Versions
Chrome ✅ (>38)
Edge ✅ (>79)
Firefox ❌ (43-52)
IE ❌ (no support)
Opera ✅ (>25)
Safari ❌ (no support)

Key: ✅ = Supported, ❌ = Not supported.

If you notice that the browser that you are using isn't supported, you should upgrade or switch it, run the code, and it should work then.


Also, another problem in your code is that you are trying to get battery.level, when battery doesn't exist. This will likely throw an error.

It looks like you want to use the returned BatteryManager object, in this case, a. So, to fix it, simply use the code below.

const m = a.level * 100 + "%";

This is now getting the level property from the already-defined a variable. When you change your code to this, it should work correctly.

Community
  • 1
  • 1
Arnav Thorat
  • 3,078
  • 3
  • 8
  • 33
1

You had an issue where you were using a variable a but were referencing battery. See my edits and working demo:

function batttick() {
  navigator.getBattery().then(battery => {
    let m = ""
    let c = ""
    m = battery.level * 100 + "%"

    if (battery.charging) {
      m += " ⚡";
      c = "green";
    }
    console.log(c, m);
    document.getElementById("batt").innerHTML = m;
    document.getElementById("batt").style.color = c;
  })
}
batttick()
<div id="batt"></div>
Lee Taylor
  • 7,761
  • 16
  • 33
  • 49