Home > Article > Web Front-end > How to get battery status using JavaScript_javascript tips
Starting from Mozilla Aurora 11, some new features have been implemented in Firefox, one of which is the basic implementation of the battery status interface. This very simple interface can provide you with information about the current battery level, whether it is charging, and some battery status change events. Let’s see the effect!
The battery object is stored in window.navigator.battery, but because this is the first time that Firefox has implemented and provided this interface, it is not yet popular. You need to use window.navigator.mozBattery. This mozBattery object has the following properties:
1.charging: Indicates whether the current battery device is charging. If the battery is not charged, this value is false. If true, the battery is charging. The current API implementation cannot get information about whether it is full, nor can it determine whether the current device has a battery.
2.chargingTime: refers to how long it takes until the battery is fully charged.
3.dischargingTime: battery usage time.
4.level: Indicates the power level, from 0 to 1.0. When this value is 0, it means that the battery is exhausted and the system is about to shut down. If it is 1.0, it means the battery is fully charged.
For these states, the interface provides corresponding events, including onchargingchange, onchargingtimechange, ondischargingtimechange, and onlevelchange. The basic usage is very simple:
// Display some useful attribute values
console.warn("Battery charging status: ", battery.charging); // true
console.warn("Battery level: ", battery.level); // 0.58
console.warn("Battery usage time: ", battery.dischargingTime);
//Set some event listeners
battery.addEventListener("chargingchange", function(e) {
console.warn("Battery charging status change: ", battery.charging);
} , false);
battery.addEventListener("chargingtimechange", function(e) {
console.warn("Battery charging time change: ", battery.chargingTime);
}, false);
battery.addEventListener("dischargingtimechange", function(e) {
console.warn("Battery time change: ", battery.dischargingTime);
}, false);
battery.addEventListener(" levelchange", function(e) {
console.warn("Battery level change: ", battery.level);
}, false);
Why use these battery programming interfaces? Because many mobile applications (non-native) packaged with browsers need to know the current state of the system. Some CPUs are very sensitive to power. The device must have sufficient power before handling certain special tasks. The App should remind the user in advance that the power is low and please charge.