Battery Status API,更多时候被称之为 Battery API, 提供了有关系统充电级别的信息并提供了通过电池等级或者充电状态的改变提醒用户的事件。 这个可以在设备电量低的时候调整应用的资源使用状态,或者在电池用尽前保存应用中的修改以防数据丢失。
Battery Status API 向 window.navigator
扩展了一个 navigator.getBattery
方法,其返回了一个battery promise, 完成后传递一个 BatteryManager
对象,并提供了一些新的可以操作电池状态的事件。
例子
在这个例子中,我们同时监听放电状态和电池等级和剩余事件的事件(不论是否正在充电还是在使用电池)。这可以通过监听 chargingchange
, levelchange
, chargingtimechange
, dischargingtimechange
事件完成。
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"); }); });
另见 标准中的例子.
标准
Specification | Status | Comment |
---|---|---|
Battery Status API | Candidate Recommendation | Initial definition |
浏览器兼容性
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 39.0 | 10 (10) moz 16 (16)[1] |
未实现 | 25 | 未实现 |
Feature | Android | Android Webview | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile | Chrome for Android |
---|---|---|---|---|---|---|---|
Basic support | 未实现 | 40.0 | 10.0 (10) moz 16.0 (16)[1] |
未实现 | 25[2] | 未实现 | 42.0[2] |
[1] Disabled by default in Firefox 10.0, but can be enabled setting the preference dom.battery.enabled
to true
. Starting with Firefox 11.0, mozBattery
is enabled by default. The Battery API is currently supported on Android, Windows, and Linux with UPower installed. Support for MacOS is available starting with Gecko 18.0 (Firefox 18.0 / Thunderbird 18.0 / SeaMonkey 2.15). Firefox also provide support for the deprecated navigator.battery
.
[2] Values for BatteryManager.chargingTime
and BatteryManager.dischargingTime
are always equal to Infinity
.