HTML5 battery API

G’day

I am happy to be back from holidays from New Zealand. Very nice place to visit. Anyway this post is about HTML5 Javascript battery API.

Currently only Firefox (latest) and Chrome (latest) supports it.

Before you jump further into this post You gotta ask yourself what are real world use cases for batter API. Let me tell you a few

  1. If your HTML5 app makes too many requests to server to get the updates from server, you can infact slow down re-polling if battery is less than N%
  2. If battery is less than n% then you may alert user when they try to access, load videos, images etc. In other words things that require more firepower from device to load.
  3. and there could be other gazillions use cases that could fit you

Above all its good to have something than nothing.

A full spec can be found here http://www.w3.org/TR/battery-status/

Lets now look at whats required to get on with Battery API

First we will get the battery object. Because only a couple of browsers have it implemented so its a good idea to get it like as shown below

navigator.battery will be available when every modern browser offers battery support. But as you can see that prefixing battery with webkit (chrome and safari) and moz (firefox) is essential at the time of writing.

 

 

Key properties of battery object

Now lets look at the key properties of battery object

  1. charging
    Represents if the system’s battery is charging.
  2. chargingTime
    Represents the time remaining in seconds until the system’s battery is fully charged.
  3. dischargingTime
    Represents the time remaining in seconds until the system’s battery is completely discharged and the system is about to be suspended.
  4. level
    This property will be most used by you perhaps if you ever touch battery API.  Represents the current battery level scaled from 0 to 1.0.

How do you use above properties is shown below

Usage

Events

What makes any Javascript API a powerful API is measured by its support for events. Battery API supports event handling for 4 of its supported properties.

Here is what you can do

 

 

As you can see that its very simple to deal with Battery events.

I hope that you will find this post helpful. Just in case if you see any error above please let me know so that it can be corrected. If you want to see a working example please let me know so that I can add a demo if required.

Cheers

 

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Comments

  1. Hi Jaspreet,

    Great post. Is there any way to get it work in webkit browser.
    The navigator.webkitBattery seems not working..

    Thanks, Sajay

Leave a Reply