navigator.getBattery cannot be found

2.7k Views Asked by At

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()
3

There are 3 best solutions below

1
Lee Taylor On BEST ANSWER

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>

0
Arnav Thorat On

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.

0
Blake O'Hare On

One common cause of this specific error message is that many browsers block the battery API if the page is not running in a secure context (HTTPS).

Check the "Secure Context Required" row of the compatibility chart: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/getBattery#browser_compatibility

Since this is now the top google search result for this error message, it's worth noting, even though this question is marked as solved.