Method to get battery status using JavaScript

  • 2020-03-30 02:49:18
  • OfStack

Since Mozilla Aurora 11, several new features have been implemented in firefox, one of which is a basic implementation of the battery state interface. This simple interface provides you with information about the battery's current level, whether it's charging, and a number of battery state events. Let's see how it works!

Battery object is stored in the window. The navigator. ', but because this is the first time the firefox browser implementation and provide the interface, not popular, you need to use the window. The navigator. MozBattery this way. This mozBattery object has the following properties:

1. Charging: indicates whether a current battery device is charging. This value is false if the battery is not charged. If true, the battery is being charged. The current API implementation cannot tell whether the device is full or not or whether it has a battery.
2. ChargingTime: how long it will take for the battery to recharge.
3. DischargingTime: battery life is up.
4. Level: represents the power level, from 0 to 1.0. When this value is 0, it means that the power is exhausted and the system is about to shut down. If 1.0, the battery is full.
For these states, the interface provides corresponding events, including onchargingchange, onchargingtimechange, ondischargingtimechange, and onlevelchange. The basic usage is simple:

//Get the battery object!
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;
//Displays some useful property values
console.warn(" Battery charging state : ", battery.charging); // true
console.warn(" Power level : ", battery.level); // 0.58
console.warn(" Battery life : ", battery.dischargingTime);
//Set up some event listeners
battery.addEventListener("chargingchange", function(e) {
 console.warn(" Battery charging state changes : ", battery.charging);
}, false);
battery.addEventListener("chargingtimechange", function(e) {
 console.warn(" Battery charging time varies : ", battery.chargingTime);
}, false);
battery.addEventListener("dischargingtimechange", function(e) {
 console.warn(" Battery life varies : ", battery.dischargingTime);
}, false);
battery.addEventListener("levelchange", function(e) {
 console.warn(" Variation of electric quantity level : ", battery.level);
}, false);

Simple, isn't it? These interfaces are great: simple, efficient, and practical!

Why use these battery programming interfaces? This is because many mobile applications packaged in a browser (not 'native') need to know the current state of the system. Some cpus are very sensitive to power. The device should have enough power before handling some special tasks. The App should warn the user in advance that the power is low, so please charge it.

Related articles: