Treehouse

JavaScript Battery API

By on  

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!

ydkjs-2.png

Recent Features

  • Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() – this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • 9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • Create a Spinning, Zooming Effect with CSS3

    In case you weren't aware, CSS animations are awesome.  They're smooth, less taxing than JavaScript, and are the future of node animation within browsers.  Dojo's mobile solution, dojox.mobile, uses CSS animations instead of JavaScript to lighten the application's JavaScript footprint.  One of my favorite effects...

  • Sexy Album Art with MooTools or jQuery

    The way that album information displays is usually insanely boring. Music is supposed to be fun and moving, right? Luckily MooTools and jQuery allow us to communicate that creativity on the web. The XHTML A few structure DIVs and the album information. The CSS The CSS...

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

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