Search code examples
javascriptfirefoxmobileuser-agentbattery

Getting Battery Level in Firefox


I am working on a project which deals with the user's current battery level. I dug around the internet but couldn't find a working solution for Firefox. I have code (see below) that works fine for Chrome (Desktop and Mobile), but not for Firefox.

Is there a solution that can be used globally for all browsers, or at least a working solution for Firefox?

window.navigator.getBattery().then(function (battery) {
  var chargingStatus = "Not Charging";

  if (String(battery.charging) == "true") chargingStatus = "Charging";
  batteryLevel.innerHTML =
    String(battery.level * 100) + "% ( " + chargingStatus + " )";

  battery.addEventListener("levelchange", function () {
    chargingStatus = "Not Charging";
    if (String(battery.charging) == "true") chargingStatus = "Charging";
    batteryLevel.innerHTML =
      String(battery.level * 100) + "% ( " + chargingStatus + " )";
  });

  battery.addEventListener("chargingchange", function () {
    chargingStatus = "Not Charging";
    if (String(battery.charging) == "true") chargingStatus = "Charging";
    batteryLevel.innerHTML =
      String(battery.level * 100) + "% ( " + chargingStatus + " )";
  });
});

Error which I get in Firefox


Solution

  • The Battery Status API is not currently supported in Mozilla Firefox (browser compatibility of Battery Status API (MDN)). It seems that Firefox 43 did have rudimentary support for an early version of the specification, but it has since been removed.

    Since the feature is considered deprecated, it's extremely unlikely Mozilla would re-add any such support now or in the future.

    The guidance on the linked MDN page says all you need to know (emphases mine):

    This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.