How to Use the HTML5 Battery Status API

Share this article

If you’re lucky, you’ll get seven or eight hours usage from a smart phone or tablet before the battery dies. Expect around half that on a laptop. Battery technology has not kept pace with advances in mobile computing. A decade ago you could expect your Palm Pilot to last up to a month on a couple of AAA batteries. Now you’re feeding devices every night and your room lights up like a blinking red and green LED version of Las Vegas. Few of us worry about battery life when developing web applications, but perhaps we should be more considerate now that mobile access has reached one in five users. Fortunately, the W3C Battery Status API has been implemented by both Mozilla and Google — and it’s very simple to use.

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
Network activity Wi-fi and mobile networks require power-draining radio wave communications. Consider: Audible and tactile output Sound and vibration will kill a battery dead; you could use shorter effects or disable it completely. Processing Heavy-duty processing has a noticeable impact on battery life and handset heat! Other than fast-action games, few web applications should require complex on-going client-side calculations. I suspect there’s little you can practically do other than suggesting the user plugs-in to continue. You should also note that many of these options may be applicable to the Page Visibility API. For example, if a game isn’t running in the active tab, it can be paused until the user returns.

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 the navigator.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.
Neither of these properties appear to work as you’d expect in current browsers. Firefox returns either zero or Infinity which isn’t particularly helpful.

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
For example, using our cross-browser 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 BucklerCraig Buckler
View Author

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.

batteryHTML5 Tutorials & ArticlesJavaScriptmobile
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week