One of the key concerns with portable devices is knowing their battery status. Mobile devices can get as little as seven or eight hours out of a full charge, whereas a laptop is lucky to get more than three or four hours. Knowing the status of the device’s battery can be important before you begin power-hungry processes or commence to download large files.
You can get information about the battery with the Battery Status API, which brings a set of attributes on the navigator.battery object. For example, to find out if the battery is currently charging, you can use the charging attribute to get a true or false value:
var batteryStatus = navigator.battery.charging;
To find the current battery level, you can use the level attribute, which returns a value from 0 (empty) to 1 (fully charged). The following code is a simple demonstration of this in action: The battery level is obtained and its value used as the value of a meter element (which will be fully introduced in Chapter 8), and the current charging status (‘Charging’ or ‘Discharging’) is appended below it. You can try it yourself in the example file battery.html. The result is shown in Figure 6-6.
var el = document.getElementById('status'),
meter = document.querySelector('meter'),
battery = navigator.battery,
status = (battery.charging) ? 'Charging' : 'Discharging';
meter.value = battery.level;
meter.textContent = battery.level;
el.textContent = status;
The battery object has two further attributes: chargingTime and dischargingTime. Both of these return a value, in seconds, of the remaining time until the battery is fully charged or fully discharged, respectively.
The Battery Status API also has a series of events that fire when a change to any of the attributes is detected: chargingchange, chargingtimechange, dischargingtimechange, and levelchange. The following code uses chargingchange to detect a change to the device’s charging status and fires an alert if the status has changed:
var status,
battery = navigator.battery,
chargeStatus = function () {
(battery.charging) ? status = 'Charging' : status = 'Discharging';
return status;
};
battery.addEventListener('chargingchange', function () {
window.alert(chargeStatus());
}, false);
window.alert(chargeStatus());
You can try this one yourself using the example file battery-event.html—plug and unplug your phone from its charger to see the status update.