HTML5获取电池状态

W3C电池状态接口定义

电池状态接口

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html>
<head>
<title>电池状态API示例</title>
<script>
window.onload = function () {
function updateBatteryStatus(battery) {
document.querySelector('#charging').textContent = battery.charging ? '正在使用交流电' : '正在使用电池';
document.querySelector('#level').textContent = battery.level;
document.querySelector('#dischargingTime').textContent = battery.dischargingTime / 60;
}
navigator.getBattery().then(function (battery) {
// Update the battery status initially when the promise resolves ...
updateBatteryStatus(battery);

// .. and for any subsequent updates.
battery.onchargingchange = function () {
updateBatteryStatus(battery);
};
battery.onlevelchange = function () {
updateBatteryStatus(battery);
};
battery.ondischargingtimechange = function () {
updateBatteryStatus(battery);
};
});
};
</script>

</head>
<body>
<div id="charging">(charging state unknown)</div>
<div id="level">(battery level unknown)</div>
<div id="dischargingTime">(discharging time unknown)</div>
</body>
</html>

参考资料

  1. 电池状态W3C规范
    http://www.w3.org/TR/battery-status/

  2. 新的 JavaScript Battery API
    http://cssha.com/battery/

  3. BatteryManager
    https://developer.mozilla.org/en-US/docs/Web/API/BatteryManager