What’s Not So Simple…
We can detect when a battery reaches a critical level but what can we do about it? It will depend on your application, but the primary causes of power drainage are… The screen Your back-lit screen is the biggest juice glutton. There are a few options you could consider when the battery reaches a critical level:- switch to a light-on-dark theme
- disable non-critical CSS3 and JavaScript animations
- avoid DOM changes where possible
- slowing down or stopping frequent Ajax polls
- using the AppCache and creating an offline app
- storing data on the client using Web Storage
- avoiding requests for non-critical assets such as images.
Browser Support
At the time of writing, only Firefox desktop and mobile editions offer unprefixed support for the Battery API (versions 10 to 16 used the moz prefix). It is also available in recent editions of Chromium with a webkit prefix. We can create a cross-browser battery object using:var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery;
if (battery) {
// battery API supported
}
This is used in the Battery API demonstration…
Basic Properties
You can obtain the battery level using thenavigator.battery.level
property which returns a value between 0 and 1, e.g.
console.log( "battery level: ", Math.floor(battery.level * 100) + "%" );
However, the current level may not be so important if the device is being charged. We can check the status using the navigator.battery.charging
property which returns true if charging or false if discharging:
console.log( "device is ", (battery.charging ? "charging" : "discharging") );
Therefore, you probably want to introduce power-boosting options when the battery level drops below, say, 25% and the device is not being charged, e.g.
var enableEffects = (battery.charging || battery.level > 0.25);
// vibrate for one second
if (enableEffects) navigator.vibrate(1000);
There are a couple of other properties you may find useful:
navigator.battery.chargingTime
— the time, in seconds, until charging reaches 100%.navigator.battery.dischargingTime
— the time, in seconds, until the battery is completely discharged and the device will shut down.
Battery Status Events
Four events can be fired by the Battery object:- chargingchange — the device has changed from being charged to being discharged or vice versa
- levelchange — the battery level has changed
- chargingtimechange — the time until the battery is fully charged has changed
- dischargingtimechange — the time until the battery is fully discharged has changed
battery
object:
battery.onlevelchange = function() {
var ee = enableEffects;
enableEffects = (battery.charging || battery.level > 0.25);
if (enableEffects != ee) {
if (enableEffects) {
console.log( "Battery power is OK." );
}
else {
console.log( "Battery power is critical!" );
}
}
}
Some would say your web app should never needlessly drain the battery. However, the Battery API allows us to make more sophisticated decisions about when we can and cannot depend on animation, effects and Ajax calls.
View the Battery API demonstration… (Firefox and Chromium)
Frequently Asked Questions (FAQs) about HTML5 Battery Status API
How does the HTML5 Battery Status API work?
The HTML5 Battery Status API is a tool that allows developers to access and use the battery status of a host device. It works by providing information about the system’s battery charge level and whether the system is charging, discharging, or the battery is ‘plugged in’. This API is event-driven, meaning it will update the status as the battery level changes or the charging state changes. It’s a powerful tool for developers to optimize the performance and power consumption of their web applications.
Is the Battery Status API supported by all browsers?
No, the Battery Status API is not supported by all browsers. As of now, it is supported by Chrome, Firefox, and Opera. However, it is not supported by Internet Explorer, Safari, and some versions of Edge. It’s always a good practice to check the compatibility of APIs with different browsers before using them in your applications.
How can I use the Battery Status API in my web application?
To use the Battery Status API in your web application, you first need to call the navigator.getBattery method, which returns a promise that will resolve to a BatteryManager object. This object provides information about the system’s battery status and also fires events when the battery level or charging state changes. Here’s a simple example:navigator.getBattery().then(function(battery) {
console.log("Battery level: " + battery.level*100 + "%");
});
What kind of information can I get from the Battery Status API?
The Battery Status API provides several pieces of information about the system’s battery. This includes the battery’s current charge level (as a percentage), whether the system is currently charging, how long it will take to charge or discharge (in seconds), and whether the battery is currently charging or discharging.
Can I use the Battery Status API to optimize my web application’s power consumption?
Yes, the Battery Status API can be a valuable tool for optimizing your web application’s power consumption. By monitoring the battery level and charging state, you can adjust your application’s behavior to conserve power when the battery level is low or the system is running on battery power. For example, you could reduce update rates or disable non-essential features to save power.
Is the Battery Status API secure?
While the Battery Status API itself does not pose a security risk, it can potentially be used by malicious websites to track users. For this reason, some browsers have removed support for the API. As a developer, it’s important to use this API responsibly and respect users’ privacy.
Can I use the Battery Status API to detect if the device is a mobile device?
While the Battery Status API can provide information about the system’s battery, it is not a reliable way to detect if the device is a mobile device. Not all mobile devices support this API, and many desktop systems also have batteries (such as laptops and some all-in-one desktops).
How can I handle Battery Status API events?
The Battery Status API fires several events that you can listen for in your application. These include ‘chargingchange’, ‘levelchange’, ‘chargingtimechange’, and ‘dischargingtimechange’. You can add event listeners for these events to update your application when the battery status changes.
Can I use the Battery Status API in a worker?
Yes, the Battery Status API can be used in a worker context. This means you can use it in a separate thread from your main application, which can help to improve performance.
What happens if the Battery Status API is not supported by the browser?
If the Battery Status API is not supported by the browser, the navigator.getBattery method will return undefined. You should always check for this in your code and provide a fallback if necessary.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.