获取电池电量 JavaScript

Get battery level JavaScript

/!\ window.navigator.battery IS STRONGLY DISCOURAGED 的使用,这个问题现在不值得检查,谢谢 /!\

我想获取当前系统的电池电量。这是我想要得到的输出:

如果是台式机(无电池) 电池电量:100%

如果是笔记本电脑 电池电量:XXX%(取决于电量)

所以我在 window.navigator.battery in my JSFiddle 上尝试了 Mozilla 基金会的代码片段。

问题: 运行 Chrome 20+版本(目前46),我在控制台还是报错:

Uncaught TypeError: Cannot read property 'addEventListener' of undefined

所以我的理解是用假定的电池电量实例化的对象 battery 没有返回任何内容。

有人已经解决了吗?

当此代码段起作用时,我的算法要点是定义用户不能针对剩余电池电量执行的操作。例如,我不希望用户进行可能会使他的电池电量降低到临界点并使关键操作失败的重动作。

来自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.

The battery property is deprecated and has been replaced by a Navigator.getBattery() method returning a battery Promise. Its support is still partial though.

警告

不要在生产中使用以下答案,因为它一直是 deprecated since then. The spec will be reworked due to privacy and security issues,所以希望看到变化和故障。

回答

为了回答我自己的问题,感谢 @Quentin 提供给我的文档的帮助,我使用 BatteryManager.level 函数实现了我的目标 BatteryManager.level =12=]。可以在此处找到提供工作片段的 link:https://developer.mozilla.org/en-US/docs/Web/API/BatteryManager/level.

以下 JSFiddle 在控制台 (F12) 中显示剩余电池的值(我无法在桌面上验证输出,所以如果它不能在桌面上工作,请纠正我):

JSFiddle

JavaScript

navigator.getBattery().then(function(battery) {

    var level = battery.level;

    console.log(level);
});

event.target.level 是事件处理程序中的级别值。

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

Navigator.getBattery() 现在已过时。虽然它在某些浏览器中可能仍然有效,但不鼓励使用它,因为它可能随时被删除。

包含作品、演示和代码
我推荐 Battery API.
你可以找到演示 here or the code here
它非常有用,提供了很多关于
的信息 电池。 免费使用。

(function() {
  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 noGood = function(error) {
    batterySupported.innerHTML = error.message;
  };

  navigator.getBattery() //returns a promise
    .then(success)
    .catch(noGood);
})();
@import url('https://fonts.googleapis.com/css2? 
   family=Roboto:wght@300&display=swap');

/* General font styles */

html {
  font-family: 'Roboto', sans-serif;
  height: 100%;
}

body {
  font-family: 'Roboto', sans-serif;
}

img {
  border: none;
  vertical-align: middle;
}


/* Basic element styles */

a {
  color: #0366d6;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

html {
  color: #000;
}

body {
  padding-top: 20px;
}

body {
  margin-bottom: 30px;
}

ul {
  margin: 10px 0;
}


/* Structure */

.container {
  background: #fff;
  border-top: none;
  text-align: center;
}

#battery-supported {
  color: #f00;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Battery API</title>
</head>

<body>

  <div class="container">
    <h1>
      Battery API demo
    </h1>

    <section class="main-content">
      <p>A demo of the Battery API</p>

      <p id="battery-supported"></p>

      <p>Battery level is <b id="battery-level"></b></p>

      <p>Battery status is <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>


    </section>

        <p class="footer">All the code is available in the <a 
href="https://github.com/robnyman/robnyman.github.com/tree/master/battery">
 Battery 
repository on GitHub</a>.</p>
  </div>




</body>

</html>