Code and Stuff

Mar 28, 2013

Battery Status (firefox)

A web page can read the level of the computer's battery (if any) and it is really easy. It is all in the window.navigator.battery object. This object has a property level that indicates the current battery level as a number between 0 and 1. There is no need to poll the value. Level changes can be tracked with the "levelchange" event. The object tells also if the battery is being charged or used and has fields with hints on charging/dischanrging times. As for the level also this values are trackable registering event handlers.

This is especially useful in web applications. For instance, with this API available, an application could be implemented so that power intensive operations like animations, audio and video are disabled, or limited to a minimum, when the battery level is getting too low. It could also return to the normal setting as soon as the power is connected.

Unfortunately, as of March 2013, I know only of Firefox that supports this W3C Candidate Recommendation.

Howto

So, here is the code. First the HTML. There is nothing that is really needed to be done in HTML to access the battery status. To display the level I simply created two DIVs, one for the whole battery the other for the current state.
<div id="battery"><div class="level"></div></div>
Also the CSS is just for the display: some round borders and backgrounds.
#battery {
  border: solid 4px darkred;
  border-radius: 8px;
  width: 80px;
  height: 200px;
  position: relative;
}

#battery .level {
  position: absolute;
  bottom: 0px;
  background-color: red;
  left:0px;
  right:0px;
}
It is the Javascript that is the most interesting. It registers an event that when triggered will update the battery indicator. Note: code uses some JQuery.
// let's be ready for webkit (they sayed they will use the prefix)
var battery = window.navigator.battery || window.navigator.webkitBattery; 

function update() {
  var level = battery.level;
  $("#battery .level").height(level * 200);

  // should probably define 3 classes, one for each color state
  if (level < 0.33) {
    $("#battery .level").css("background-color","red");
    $("#battery").css("border-color","darkred");
  } else if (level < 0.66) {
    $("#battery .level").css("background-color","yellow");
    $("#battery").css("border-color","brown");
  } else {
    $("#battery .level").css("background-color","lightgreen");
    $("#battery").css("border-color","darkgreen");
  }
}

// and finally when the DOM is ready let's update and register the event
$(function(){
  if (battery == undefined) {
    // sorry no battery status api support
    return;
  }

  update();

  // and here we register the event
  battery.addEventListener('levelchange', update, false);
});

Links

Here a few links to other people's posts about this: