W3C

Battery Status API

W3C Working Draft 29 November 2011

This version:
http://www.w3.org/TR/2011/WD-battery-status-20111129/
Latest published version:
http://www.w3.org/TR/battery-status/
Latest editor's draft:
http://dev.w3.org/2009/dap/system-info/battery-status.html
Previous version:
http://www.w3.org/TR/2011/WD-battery-status-20110915/
Editor:
Anssi Kostiainen, Nokia

Abstract

This specification defines an API that provides information about the battery status of the hosting device.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

The functionality described in this specification was initially specified as part of the System Information API but has been extracted in order to be more readily available, more straightforward to implement, and in order to produce a specification that could be implemented on its own merits without interference with other, often unrelated, features.

This document was published by the Device APIs Working Group as a Last Call Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-device-apis@w3.org (subscribe, archives). The Last Call period ends 20 December 2011. All feedback is welcome.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This is a Last Call Working Draft and thus the Working Group has determined that this document has satisfied the relevant technical requirements and is sufficiently stable to advance through the Technical Recommendation process.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

The Battery Status API specification defines a means for web developers to programmatically determine the battery status of the hosting device. Without knowing the battery status of a device, a web developer must design the web application with an assumption of sufficient battery level for the task at hand. This means the battery of a device may exhaust faster than desired because web developers are unable to make decisions based on the battery status. Given knowledge of the battery status, web developers are able to craft web content and applications which are power-efficient, thereby leading to improved user experience.

The Battery Status API can be used to defer or scale back work when the device is not charging in or is low on battery. An archetype of an advanced web application, a web-based email client, may check the server for new email every few seconds if the device is charging, but do so less frequently if the device is not charging or is low on battery. Another example is a web-based word processor which could monitor the battery level and save changes before the battery runs out to prevent data loss.

The following example shows how a web-based email client could check for new emails every ten seconds without knowledge of the battery status:

<!DOCTYPE html>
<html>
<head>
  <title>Email Client</title>
  <script>
    var mail = {
      INTERVAL_DEFAULT: 1000 * 10,
      interval: null,
      timer: 0,

      check: function () {
        console.log('Checking the server for new emails using an interval of ' + 
                    (mail.interval / 1000) + ' seconds.');
      },
      
      setTimer: function (interval) {
        if (interval === mail.interval) { return; }
        if (mail.timer !== 0) { clearTimeout(mail.timer); }
        if (interval) { mail.timer = setInterval(function () { mail.check(); }, interval); }
        mail.interval = interval;
      }
    };

    window.addEventListener('load', function () {
      mail.setTimer(!mail.interval ? mail.INTERVAL_DEFAULT : mail.interval);
    }, false);
  </script>
</head>
<body></body>
</html>

The script will always check for emails every ten seconds, even if the battery level is critically low and the device is not charging. This is an example of poor resource management.

Using the BatteryManager interface, the web application is, for example, able to throttle checking for emails if the device is low on battery, stop checking for emails if the battery is critically low and resume normal operation when the battery is charging:

<!DOCTYPE html>
<html>
<head>
  <title>Battery-aware Email Client</title>
  <script>
    var mail = {
      INTERVAL_BATTERY_LOW: 1000 * 60 * 10,
      INTERVAL_DEFAULT: 1000 * 10,
      interval: null,
      timer: 0,
      
      check: function () {
        console.log('Checking the server for new emails using an interval of ' + 
                    (mail.interval / 1000) + ' seconds.');
      },
      
      setTimer: function (interval) {
        if (interval === mail.interval) { return; }
        if (mail.timer !== 0) { clearTimeout(mail.timer); }
        if (interval) { mail.timer = setInterval(function () { mail.check(); }, interval); }
        mail.interval = interval;
      }
    };
    
    window.addEventListener('load', function () {
      mail.setTimer(!mail.interval ? mail.INTERVAL_DEFAULT : mail.interval);
    }, false);
    
    var battery = navigator.battery;
    
    battery.addEventListener('dischargingtimechange', function () {
      if (battery.dischargingTime < 60 * 30 || battery.level < 0.1) {
        mail.setTimer(mail.INTERVAL_BATTERY_LOW);
        console.log('30 minutes remaining or level below 10%, checking the server less frequently.');
      } else if (battery.dischargingTime < 60 * 10 || battery.level < 0.05) {
        mail.setTimer(null);
        console.log('10 minutes remaining or level below 5%, stop checking the server.');
      }
    }, false);
    
    battery.addEventListener('chargingchange', function () {
      if (battery.charging) {
        mail.setTimer(mail.INTERVAL_DEFAULT);
        console.log('Battery is charging, checking the server normally.');
      }
    }, false);
  </script>
</head>
<body></body>
</html>

2. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words must, must not, required, should, should not, recommended, may, and optional in this specification are to be interpreted as described in [RFC2119].

This specification defines conformance criteria that apply to a single product: the user agent that implements the interfaces that it contains.

Implementations that use ECMAScript to implement the APIs defined in this specification must implement them in a manner consistent with the ECMAScript Bindings defined in the Web IDL specification [WEBIDL], as this specification uses that specification and terminology.

4. BatteryManager Interface

[NoInterfaceObject]
interface BatteryManager : EventTarget {
    readonly attribute boolean   charging;
    readonly attribute double    chargingTime;
    readonly attribute double    level;
    readonly attribute double    dischargingTime;
             attribute Function? onchargingchange;
             attribute Function? onchargingtimechange;
             attribute Function? onlevelchange;
             attribute Function? ondischargingtimechange;
};

4.1 Attributes

charging of type boolean, readonly
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.
No exceptions.
chargingTime of type double, readonly
Represents the time remaining in seconds until the system's battery is fully charged. The attribute must be set to 0, if the battery is full or there is no battery attached to the system, and to the value positive Infinity if the battery is discharging, the implementation is unable to report the remaining charging time, or otherwise.
No exceptions.
dischargingTime of type double, readonly
Represents the time remaining in seconds until the system's battery is completely discharged and the system is about to be suspended. The attribute must be set to the value positive Infinity, if the battery is charging, the implementation is unable to report the remaining discharging time, there is no battery attached to the system, or otherwise.
No exceptions.
level of type double, readonly
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.
No exceptions.
onchargingchange of type Function, nullable
No exceptions.
onchargingtimechange of type Function, nullable
No exceptions.
ondischargingtimechange of type Function, nullable
No exceptions.
onlevelchange of type Function, nullable
No exceptions.

When a BatteryManager object is created, charging must be set to true, chargingTime to 0, level to 1.0 and dischargingTime to the value positive Infinity, if the implementation is unable to report the battery's charging state, charging time, level or remaining time respectively.

When the value of charging, chargingTime, level or dischargingTime attribute changes, the user agent must fire a simple event [HTML5], which does not bubble and is not cancelable, named chargingchange, chargingtimechange, levelchange or dischargingtimechange respectively at the BatteryManager object.

The definition of how often the chargingtimechange, levelchange and dischargingtimechange events are fired is left to the implementation.

5. Examples

This section is non-normative.

This trivial example writes the battery level to the console each time the level changes:

navigator.battery.onlevelchange = function () {
  console.log(navigator.battery.level);
};

Alternatively, the same using the addEventListener() method:

navigator.battery.addEventListener('levelchange', function () {
  console.log(navigator.battery.level);
}, false);

The following example updates the indicators to show the charging state, level and time remaining in minutes:

<!DOCTYPE html>
<html>
<head>
  <title>Battery Status API Example</title>
  <script>
    var battery = navigator.battery;
    
    battery.onchargingchange = function () {
      document.querySelector('#charging').textContent = battery.charging ? 'charging' : 'not charging';
    };

    battery.onlevelchange = function () {
      document.querySelector('#level').textContent = battery.level;
    };

    battery.ondischargingtimechange = function () {
      document.querySelector('#dischargingTime').textContent = battery.dischargingTime / 60;
    };
  </script>
</head>
<body>
  <div id="charging">(charging state unknown)</div>
  <div id="level">(battery level unknown)</div>
  <div id="dischargingTime">(discharging time unknown)</div>
</body>
</html>

A. Acknowledgements

Big thanks to the Mozilla WebAPI team for their invaluable feedback based on prototype implementations. Many thanks to the people behind the System Information API and Device Orientation Event specification for the initial inspiration. Also thanks to the nice folks bringing us the Page Visibility specification, which motivated the editor of this specification to write the introduction chapter discussing some real-world high value use cases that apply equally to this specification. Special thanks to all the participants of the Device APIs Working Group and others who have sent in substantial feedback and comments, and made the Web a better place for everyone by doing so.

B. References

B.1 Normative references

[HTML5]
Ian Hickson; David Hyatt. HTML5. 25 May 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/html5
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[WEBIDL]
Cameron McCormack. Web IDL. 19 December 2008. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2008/WD-WebIDL-20081219

B.2 Informative references

No informative references.