W3C

Battery Status Events

W3C Working Draft 15 September 2011

This version:
http://www.w3.org/TR/2011/WD-battery-status-20110915/
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-20110602/
Editor:
Anssi Kostiainen, Nokia

Abstract

This specification defines new DOM event types that provide 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 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). 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 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 Events specification defines a means for web developers to programmatically determine the battery status of the hosting device and whether the device is plugged in or not. 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 Events can be used to defer or scale back work when the device is not plugged 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 plugged in, but do so less frequently if the device is not plugged in 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 plugged in. This is an example of poor resource management.

Using the batterylow, batterycritical and batteryok event types, 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 status is OK:

<!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 = new BatteryStatusEventSource();
    
    battery.addEventListener('batterylow', function () {
      mail.setTimer(mail.INTERVAL_BATTERY_LOW);
      console.log('Low battery, checking the server less frequently.');
    }, false);
    
    battery.addEventListener('batterycritical', function () {
      mail.setTimer(null);
      console.log('Critically low battery, stopped checking the server.');
    }, false);
    
    battery.addEventListener('batteryok', function () {
      mail.setTimer(mail.INTERVAL_DEFAULT);
      console.log('Battery ok, 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.

3. BatteryStatusEventSource Interface

[Constructor]
interface BatteryStatusEventSource : EventTarget {
    attribute Function? onbatterystatus;
    attribute Function? onbatterylow;
    attribute Function? onbatterycritical;
    attribute Function? onbatteryok;
};

3.1 Attributes

onbatterycritical of type Function, nullable
No exceptions.
onbatterylow of type Function, nullable
No exceptions.
onbatteryok of type Function, nullable
No exceptions.
onbatterystatus of type Function, nullable
No exceptions.

The onbatterystatus, onbatterylow, onbatterycritical and onbatteryok event handlers, and their corresponding event handler event types batterystatus, batterylow, batterycritical and batteryok respectively must be supported as IDL attributes by all objects implementing the BatteryStatusEventSource interface.

3.2 Constructor

The BatteryStatusEventSource() constructor must be visible when the script's global object is either a Window object [HTML5] or an object implementing the WorkerUtils interface [WEBWORKERS].

When the constructor is invoked, the user agent must run the following algorithm:

  1. Instantiate a new BatteryStatusEventSource object, and let battery be that object.
  2. Enable battery's task source.
  3. Return battery.

When the battery object has no registered event listeners, its task source can be disabled as an implementation optimization technique.

4. BatteryStatusEvent Interface

This interface defines the batterystatus, batterylow, batterycritical and batteryok event types.

[Constructor(DOMString type, optional BatteryStatusEventInit eventInitDict)]
interface BatteryStatusEvent : Event {
    readonly attribute boolean    isPlugged;
    readonly attribute float?     level;
    readonly attribute DOMString? status;
};
dictionary BatteryStatusEventInit : EventInit { boolean isPlugged; float? level; DOMString? status; };

4.1 Attributes

isPlugged of type boolean, readonly
Represents whether the device is plugged in. If the device is plugged in and its battery is being charged or is at its full capacity, then isPlugged must be set to true, otherwise false. If the device does not have a battery, then isPlugged must be set to true.
No exceptions.
level of type float, readonly, nullable
Represents how much of the internal power source remains, scaled from 0 to 100. A value of 0 indicates that the system's battery is depleted, i.e. it is about to be suspended. If the implementation is unable to report the battery's level, or there is no battery attached to the system, then level must be set to null.
No exceptions.
status of type DOMString, readonly, nullable
One of "critical", "low", "ok" or null. Represents the battery status of the hosting device, scaled from critical to ok. If the implementation is unable to report the battery's level, then status must be set to null. If the device does not have a battery, then status must be set to ok.

The following table represents the relationship between status, isPlugged and level attributes, and corresponding events. The definitions of low_threshold and critical_threshold are left to the implementation.

status isPlugged level Corresponding event
critical false 0 ≤ levelcritical_threshold batterycritical
low false critical_threshold < level < low_threshold batterylow
ok false low_thresholdlevel ≤ 100 batteryok
ok true 0 ≤ level ≤ 100 batteryok
null true or false null
No exceptions.

4.2 Dictionary BatteryStatusEventInit Members

isPlugged of type boolean
level of type float, nullable
status of type DOMString, nullable

4.3 Constructor

BatteryStatusEvent(type, eventInitDict) is an event constructor, as defined in [DOM4].

When the user agent is required to dispatch the event, then it must run the following algorithm:

  1. Create an event that uses the BatteryStatusEvent interface as defined in [DOM4], which bubbles, and is cancelable, and has no default action.
  2. Queue a task to dispatch the newly created event at the BatteryStatusEventSource object.

4.4 The batterystatus event

The user agent must dispatch this event type at the BatteryStatusEventSource object when a change in the battery status of the hosting device occurs as follows:

When the status attribute changes its value to low, critical or ok, then the user agent must dispatch the BatteryStatusEvent event of type batterylow, batterycritical or batteryok respectively before dispatching the BatteryStatusEvent event of type batterystatus.

Type batterystatus
Interface BatteryStatusEvent if generated by the user agent, Event otherwise.
Sync / Async Async
Bubbles Yes
Target defaultView
Cancelable Yes
Default action none
Context info Event.target: defaultView

4.5 The batterylow event

The user agent must dispatch this event type at the BatteryStatusEventSource object when a change in the battery status of the hosting device occurs as follows:

The definition of a low battery condition is left to the implementation.

The condition corresponds to the value of low of the status attribute on the BatteryStatusEvent interface.

Type batterylow
Interface BatteryStatusEvent if generated by the user agent, Event otherwise.
Sync / Async Async
Bubbles Yes
Target defaultView
Cancelable Yes
Default action none
Context info Event.target: defaultView

4.6 The batterycritical event

The user agent must dispatch this event type at the BatteryStatusEventSource object when a change in the battery status of the hosting device occurs as follows:

In the critically low battery condition the battery level is lower than in the low battery condition. Otherwise, the definition of a critically low battery condition is left to the implementation.

The condition corresponds to the value of critical of the status attribute on the BatteryStatusEvent interface.

Type batterycritical
Interface BatteryStatusEvent if generated by the user agent, Event otherwise.
Sync / Async Async
Bubbles Yes
Target defaultView
Cancelable Yes
Default action none
Context info Event.target: defaultView

4.7 The batteryok event

The user agent must dispatch this event type on the BatteryStatusEventSource object when a change in the battery status of the hosting device occurs as follows:

The condition corresponds to the value of ok of the status attribute on the BatteryStatusEvent interface.

Type batteryok
Interface BatteryStatusEvent if generated by the user agent, Event otherwise.
Sync / Async Async
Bubbles Yes
Target defaultView
Cancelable Yes
Default action none
Context info Event.target: defaultView

5. Examples

This section is non-normative.

Register to receive repeated BatteryStatusEvent events:

var battery = new BatteryStatusEventSource();

battery.addEventListener('batterystatus', function (event) {
  console.log(event.level);
}, false);

Register to receive a single BatteryStatusEvent event:

var battery = new BatteryStatusEventSource();

var handler = function (event) {
  console.log(event.level);
  battery.removeEventListener('batterystatus', handler, false);
};

battery.addEventListener('batterystatus', handler, false);

Register to receive a BatteryStatusEvent of type batterylow:

var battery = new BatteryStatusEventSource();

battery.addEventListener('batterylow', function () {
  console.log('The battery is low.');
}, false);

Register to receive a BatteryStatusEvent of type batterycritical:

var battery = new BatteryStatusEventSource();

battery.addEventListener('batterycritical', function () {
  console.log('The battery is critically low.');
}, false);

Register to receive a BatteryStatusEvent of type batteryok:

var battery = new BatteryStatusEventSource();

battery.addEventListener('batteryok', function () {
  console.log('The battery is ok.');
}, false);

The following example updates the indicators to show whether or not the device is plugged in and what is the current battery level and status:

<!DOCTYPE html>
<html>
<head>
  <title>Battery Status Event Example</title>
  <script>
    var battery = new BatteryStatusEventSource();
  
    battery.addEventListener('batterystatus', function (event) {
      document.querySelector('#plugged').textContent = event.isPlugged ? 'plugged' : 'not plugged';
      document.querySelector('#level').textContent = event.level;
      document.querySelector('#status').textContent = event.status;
    }, false);
  </script>
</head>
<body>
  <div id="plugged">(plugged state unknown)</div>
  <div id="level">(battery level unknown)</div>
  <div id="status">(battery status unknown)</div>
</body>
</html>

A. Acknowledgements

Many thanks to the people behind the System Information API and Device Orientation Event specification for 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 while doing so.

B. References

B.1 Normative references

[DOM4]
Anne van Kesteren; Ms2ger. DOM4. 7 September 2011. W3C Editor's Draft. (Work in progress.) URL: http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html
[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
[WEBWORKERS]
Ian Hickson. Web Workers. 10 March 2011. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2011/WD-workers-20110310/

B.2 Informative references

No informative references.