在 Firefox 中获取电池电量

Getting Battery Level in Firefox

我正在进行一个处理用户当前电池电量的项目。我在互联网上四处搜寻,但找不到适用于 Firefox 的有效解决方案。我的代码(见下文)适用于 Chrome(桌面和移动),但不适用于 Firefox。

是否有可以在全球范围内用于所有浏览器的解决方案,或者至少有一个适用于 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

Battery Status API is not currently supported in Mozilla Firefox (browser compatibility of Battery Status API (MDN)). It seems that Firefox 43 确实对规范的早期版本提供了基本支持,但此后已被删除。

由于该功能被认为已弃用,因此 Mozilla 现在或将来不太可能重新添加任何此类支持。

链接的 MDN 页面上的指南说明了所有你需要知道的(强调我的):

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.