From Mozilla Aurora 11, Firefox has implemented some new features, one of which is the basic implementation of the battery state interface. This simple interface can provide you with information about the current battery charge, whether it is charging, and some of the battery state change events. Let's see the effect!
The battery object is stored in the window.navigator.battery, but because this is the first time Firefox browser to implement and provide this interface, not universal, you need to use window.navigator.mozBattery this notation. This Mozbattery object has the following properties:
1.charging: Indicates whether the current battery device is charging. This value is False if the battery is not charged. If true, indicates that the battery is charging. The current API implementation does not get full information and cannot determine whether the current device has a battery.
2.chargingTime: How long does it take to distance the battery?
3.dischargingTime: The battery has been in use time.
4.level: The level of electricity, from 0 to 1.0. When this value is 0 o'clock, the battery is running out and the system is about to shut down. If 1.0, the battery is full power.
For these states, the interfaces provide the corresponding events, including Onchargingchange, Onchargingtimechange, Ondischargingtimechange, and Onlevelchange. The basic usage is simple:
Copy Code code as follows:
Get the Battery Object!
var battery = Navigator.battery | | Navigator.webkitbattery | | Navigator.mozbattery;
Show some useful property values
Console.warn ("Battery charge Status:", battery.charging); True
Console.warn ("Level of Electricity:", battery.level); 0.58
Console.warn ("Battery Use time:", battery.dischargingtime);
Set up some event listeners
Battery.addeventlistener ("Chargingchange", function (e) {
Console.warn ("Battery charge status change:", battery.charging);
}, False);
Battery.addeventlistener ("Chargingtimechange", function (e) {
Console.warn ("Battery Charge time change:", battery.chargingtime);
}, False);
Battery.addeventlistener ("Dischargingtimechange", function (e) {
Console.warn ("Battery Use time change:", battery.dischargingtime);
}, False);
Battery.addeventlistener ("Levelchange", function (e) {
Console.warn ("Change of electricity level:", battery.level);
}, False);
It's simple, isn't it? These interfaces are very good: simple, efficient, practical!
Why do you use these battery programming interfaces? Because many mobile apps that are packaged in browsers (not ' native ') need to know the current state of the system. Some CPUs are sensitive to electricity, and the device should have enough power before handling certain special tasks, and the app should alert the user to a low charge.