提供了有关系统充电级别的信息并提供了通过电池等级或者充电状态的改变提醒用户的事件,Battery Status API 向 window.navigator 扩展了一个 navigator.getBattery 方法,其返回了一个 battery promise, 完成后传递一个 BatteryManager 对象,并提供了一些新的可以操作电池状态的事件。
navigator.getBattery().then(function (battery) {
console.log('Battery charging? ' + (battery.charging ? 'Yes' : 'No'))
console.log('Battery level: ' + battery.level * 100 + '%')
console.log('Battery charging time: ' + battery.chargingTime + ' seconds')
console.log(
'Battery discharging time: ' + battery.dischargingTime + ' seconds'
)
battery.addEventListener('chargingchange', function () {
console.log('Battery charging? ' + (battery.charging ? 'Yes' : 'No'))
})
battery.addEventListener('levelchange', function () {
console.log('Battery level: ' + battery.level * 100 + '%')
})
battery.addEventListener('chargingtimechange', function () {
console.log('Battery charging time: ' + battery.chargingTime + ' seconds')
})
battery.addEventListener('dischargingtimechange', function () {
console.log(
'Battery discharging time: ' + battery.dischargingTime + ' seconds'
)
})
})