O'Reilly

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!

Track.js Error Reporting

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...

  • CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

Incredible Demos

  • CSS Kwicks

    One of the effects that made me excited about client side and JavaScript was the Kwicks effect.  Take a list of items and react to them accordingly when hovered.  Simple, sweet.  The effect was originally created with JavaScript but come five years later, our...

  • MooTools-Like Element Creation in jQuery

    I really dislike jQuery's element creation syntax. It's basically the same as typing out HTML but within a JavaScript string...ugly! Luckily Basil Goldman has created a jQuery plugin that allows you to create elements using MooTools-like syntax. Standard jQuery Element Creation Looks exactly like writing out...

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?

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

Recently on David Walsh Blog

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...