This article mainly introduces how to use JavaScript to obtain the battery status. For more information, see Mozilla Aurora 11. Firefox has implemented some new functions, one of them is the basic implementation of the battery Status interface. This simple interface provides information about the current battery power, whether the battery is being charged, and some battery status change events. Let's take a look at the effect!
Battery objects are stored in window. navigator. battery, but this is the first time Firefox has implemented and provided this interface, and is not widely used. You need to use window. navigator. mozBattery. This batch battery object has the following attributes:
1. charging: indicates whether the current battery device is being charged. This value is false if the battery is not charged. If true, the battery is being charged. The current API implementation cannot obtain information that is full or whether the current device has a battery.
2. chargingTime: it refers to how long it will take to fill the battery.
3. dischargingTime: Battery time in use.
4. level: indicates the power level, from 0 to 1.0. When this value is 0, it indicates that the power is exhausted and the system is about to shut down. If the value is 1.0, the battery is fully powered.
For these statuses, the interface provides corresponding events, including onchargingchange, onchargingtimechange, ondischargingtimechange, and onlevelchange. The basic usage is simple:
The Code is as follows:
// Obtain the battery object!
Var battery = navigator. battery | navigator. webkitBattery | navigator. mozBattery;
// Display some useful property values
Console. warn ("battery charging status:", battery. charging); // true
Console. warn ("power level:", battery. level); // 0.58
Console. warn ("battery 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 usage time change:", battery. dischargingTime );
}, False );
Battery. addEventListener ("levelchange", function (e ){
Console. warn ("Power level Change:", battery. level );
}, False );
It's easy, isn't it? These interfaces are very good: simple, efficient, and practical!
Why use these battery programming interfaces? Because many mobile applications (not 'native ') encapsulated by browsers need to know the current status of the system. Some CPUs are very sensitive to power usage. Before processing certain special tasks, the device must have enough power. The App should notify the user of insufficient power in advance, so please charge.