JavaScript Battery API

By  on  

The Battery API has been updated; read JavaScript Battery API Update to see the new code pattern!

Mozilla Aurora 11 was recently released with a bevy of new features. One of those great new features is their initial implementation of the Battery Status API. This simple API provides you information about the battery's current charge level, its charging status, and allows you to be notified of changes via a few events. Let's check it out!

The battery object is located at window.navigator.battery, but since this is Mozilla's initial offering and the API is not yet cemented, you'll need to use window.navigator.mozBattery. The helpful mozBattery properties include:

  • charging: Represents if the system's battery is charging. The attribute must be set to false if the battery is discharging, and set to true, if the battery is charging, full, the implementation is unable to report the state, or there is no battery attached to the system, or otherwise.
  • chargingTime: Represents the time remaining in seconds until the system's battery is fully charged.
  • dischargingTime: Represents the time remaining in seconds until the system's battery is completely discharged and the system is about to be suspended.
  • level: Represents the current battery level scaled from 0 to 1.0. The attribute must be set to 0 if the system's battery is depleted and the system is about to be suspended, and to 1.0 if the battery is full, the implementation is unable to report the battery's level, or there is no battery attached to the system.

Events for each of these statuses are provided, including onchargingchange, onchargingtimechange, ondischargingtimechange, and onlevelchange. Basic usage is simple:

// Get the battery!
var battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery;

// A few useful battery properties
console.warn("Battery charging: ", battery.charging); // true
console.warn("Battery level: ", battery.level); // 0.58
console.warn("Battery discharging time: ", battery.dischargingTime);

// Add a few event listeners
battery.addEventListener("chargingchange", function(e) {
	console.warn("Battery charge change: ", battery.charging);
}, false);
battery.addEventListener("chargingtimechange", function(e) {
	console.warn("Battery charge time change: ", battery.chargingTime);
}, false);
battery.addEventListener("dischargingtimechange", function(e) {
	console.warn("Battery discharging time change: ", battery.dischargingTime);
}, false);
battery.addEventListener("levelchange", function(e) {
	console.warn("Battery level change: ", battery.level);
}, false);

I promised a simple API, didn't I? The battery API is the perfect API: simple, effective, and focused!

So why use the battery API? Since many mobile apps live inside a browser wrapper (aren't completely "native"), it's great to have access to system information. Some processes are power-intensive and it may bear warning the user before starting the process that their device is low on battery. Either way, this simple API's true usefulness should become apparent soon!

Recent Features

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

  • By
    Camera and Video Control with HTML5

    Client-side APIs on mobile and desktop devices are quickly providing the same APIs.  Of course our mobile devices got access to some of these APIs first, but those APIs are slowly making their way to the desktop.  One of those APIs is the getUserMedia API...

  • By
    MooTools Documentation Search Favelet

    I'm going to share something with you that will blow your mind: I don't have the MooTools documentation memorized. I just don't. I visit the MooTools docs frequently to figure out the order of parameters of More classes and how best to use...

Discussion

  1. One simple use case is when you’re having this huge ass survey system, where it could take to over 30 minutes to complete the survey. You might want to check if the user has a charger in place. Even if your application is really good at saving data, it’s still a pain for a user to come back to a long and dreading survey in the first place. Why take any risks? ;-)

    • Alex

      You could be saving the data into the browser local storage periodically in this scenario :P

      I personally can’t find any uses for this, except maybe for adding some easter egg stuff…

  2. We can use it also for disabling/enabling some javascript features like animations and graphics that eat some enegie depending on the device charges.

  3. For a long time I’ve wanted to be able o benchmark code not by execution speed, but by CPU/power consumption, especially as various components of execution are more and more split between the CPU and GPU.

    I can see a scenario where, even though certain code takes longer to execute, it might use less power due to running code optimized for GPU usage.

    Thanks for the clear explanation of the API! Also, go Madison! I’ve been reading posts from your blog for years and never realized you live there!

  4. I’m working on desktop now, so…

    Is there a way to emulate OS battery state to completely test app performance?

  5. I just released a tiny wrapper for the Battery Status API. It’s available on GitHub: https://github.com/pstadler/battery.js

  6. Igans

    This is probably one of the most pointless APIs I’ve ever heard, and I think it violates privacy.
    Don’t get me wrong here, it is cool from a point of view of a developer, but computers not always can reliably calculate things like time till discharge. Some developers might not implement this API properly and for example ignore the case when user will connect his/her laptop with a cord.
    On the other hand, this is nice API for malicious websites, they can now make more intelligent scams: e.g. you have X minutes left of battery life, but with our software your battery will discharge 10% longer.
    Instead of wasting time on this, finish HTML5 and make it so that video would have at least one codec what would work across all platforms and browsers. That would be way more useful.

  7. I would beg to differ with Igans here. This API is extremely useful to mobile developers, and will result in better web based apps for the mobile end user.

    For example, if we are developing a web based version of a mobile mapping/navigation app that uses frequent GPS updates from the device (a battery intensive operation), determining the battery charge state is essential in setting the update frequency. In this way, users on battery will have fewer updates, extending battery life, while a device plugged in to a charger can update at the optimal frequency for position accuracy.

    Without such an API, eveyone is stuck with a battery draining app or some sort of compromise .

    Your suggestion of malicious use of an API with read-only methods is ridiculous. A malicious site could just as easily do exactly what you described whether the API exists or not.

  8. privacy knowledge

    commom users of firefox do not know that their battery info is leaked to websites they visit

    it is enabled by default

    the setting is hidden

    and yes it is a breach of the privacy

    the fact that my device has an accu or not reveals info the fact that i charge it or not too

    combine that with information leaked in the user agent, referrer, ip lookup, and they can make a nice profile of you

    not even speaking about flash javascript and cookies and dom storage

    they can know if you are on a mobile device laptop/tablet/smartphone, what os, what isp, what country what language

    it is too much and it is hidden in the about:config common user dont know and are tracked and profiled etc crackers can gather all this information and use it to find out the best way to attack you and steal or destroy what ever is in their mind

  9. I am a little confused by the term battery here? Because there is no battery in desktop machines, is this function meant for laptops and android driven mobile phones?

  10. Tnx for the nice post. Thought I’d leave a small comment with a even nicer demo: https://elgervanboxtel.nl/blog/#/post/battery-api

    Don’t forget to plugin or unplug the power cable while viewing ;-)

    Enjoy!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!