Wake Lock API

W3C Editor's Draft

This version:
https://w3c.github.io/wake-lock/
Latest published version:
https://www.w3.org/TR/wake-lock/
Latest editor's draft:
https://w3c.github.io/wake-lock/
Test suite:
https://w3c-test.org/wake-lock/
Implementation report:
https://www.w3.org/2009/dap/wiki/ImplementationStatus
Editor:
Kenneth Rohde Christiansen ( Intel Corporation )
Former editors:
Ilya Bogdanovich (Yandex)
Andrey Logvinov (Yandex)
Marcos Caceres (Mozilla)
Participate:
GitHub w3c/wake-lock
File a bug
Commit history
Pull requests
Quality Assurance Lead:
Wanming Lin (Intel)
Use cases:
Use Cases and Requirements
Implementation status:
Blink

Abstract

This document specifies an API that allows web applications to request a wake lock. A wake lock prevents some aspect of the device from entering a power-saving state (e.g., preventing the system from turning off the screen).

Status of This Document

This is a preview

Do not attempt to implement this version of the specification. Do not reference this version as authoritative in any way. Instead, see https://w3c.github.io/wake-lock/ for the Editor's draft.

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 https://www.w3.org/TR/.

Implementors need to be aware that this specification is extremely unstable. Implementors who are not taking part in the discussions will find the specification changing out from under them in incompatible ways. Vendors interested in implementing this specification before it eventually reaches the Candidate Recommendation phase should subscribe to the repository on GitHub and take part in the discussions.

This document was published by the Device APIs Working Group as an Editor's Draft.

GitHub Issues are preferred for discussion of this specification. Alternatively, you can send comments to our mailing list. Please send them to public-device-apis@w3.org ( archives ).

Please see the Working Group's implementation report .

Publication as an Editor's 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 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 .

This document is governed by the 1 February 2018 W3C Process Document .

1. Wake Locks

A wake lock prevents some aspect of the device or operating system from entering a power-saving state.

This specification defines two wake lock types :

  1. Screen wake lock which prevents device's screen from turning off so that the user can still see the information displayed on the screen.
  2. System wake lock which prevents device's CPU from entering a standby mode so that the programs can continue running.
Note
One type of wake lock can imply the effects of another: for example, screen wake lock logically implies that the program which displays information on the screen continues running, as if the system wake lock were also applied. But to avoid dependence on such implementation details which may not always be true, this specification treats all types of wake locks as independent.

A user agent can deny wake lock of a particular type for a particular Document by any implementation-specific reason, for example, a user or platform setting or preference.

The wake lock feature is a policy-controlled feature with feature name wake-lock and default allowlist ["self"] .

Note

The default allowlist of ["self"] allows wake lock usage in same-origin nested frames but prevents third-party content from using wake locks.

Third-party usage can be selectively enabled by adding allow="wake-lock" attribute to the frame container element:


<

iframe


src

=

"https://third-party.com"


allow

=

"wake-lock"

/>


</

iframe

>

Alternatively, the wake lock feature can be disabled completely by specifying the feature policy in a HTTP response header:


Feature-Policy
:
{"wake-lock":
[]}

See [ FEATURE-POLICY ] for more details.

2. The WakeLockType enum

For the purpose of wake lock type description, this specification defines the following enumeration:


enum



WakeLockType



{

"


screen


"
,

"


system


"

};

screen
Screen wake lock type.
system
System wake lock type.

3. Extensions to Wake lock state associated with the Navigator interface settings object

[ };

For each Navigator The relevant settings object object, there is of the active document of a browsing context has an associated wake lock resolution state record with the following internal slots :

Internal Slot Initial value Description ( non-normative )
[[RequestCounter]] A set with entries for each wake lock type which is one of: with the values equal to 0. The values indicates the amount of current requests per wake lock type . A number greater than zero indicates an outstanding wake lock request

4. Extensions to the WakeLock Navigator object Rejected wake lock resolution Pending wake lock resolution Each wake lock resolution interface is initially set to pending wake lock resolution .

partial interface Navigator {
  [SecureContext] Promise<WakeLock> getWakeLock(WakeLockType type);
};

The getWakeLock() method, when invoked with an argument type , MUST run the following steps:

  1. Let p be a new Promise object. Let document be the responsible document of the current settings object .
  2. If Let context be the document 's browsing context .
  3. If context is not allowed to use the policy-controlled feature named wake-lock null , reject p return a new Promise object, rejected with a " SecurityError NotSupportedError " DOMException and return p . .
  4. Let resolution p be the wake lock resolution for the wake lock type a new Promise type . object.
  5. If resolution document is a pending wake lock resolution and the user agent does not support the wake lock type denoted by type , or has otherwise determined it will deny wake lock of this type for document , set resolution allowed to rejected wake lock resolution . If resolution is a pending wake lock resolution use and the user agent has determined it will not deny wake lock of this type for document , create and initialize a wake lock object policy-controlled feature of type type and set resolution be that object. If resolution is rejected wake lock resolution , named " wake-lock ", reject p with a " NotSupportedError SecurityError " DOMException and return p .
  6. If resolution is a WakeLock object, resolve p with resolution and return p . Run the following steps in parallel :
    1. If the user agent denies the wake lock of this type for document , set resolution to rejected wake lock resolution , reject p with " NotSupportedError " and abort these steps.
    2. Let lock be the result of Create create and initialize a wake lock object of type type and set resolution to that object. .
    3. Resolve p with resolution lock .
  7. Return p .

4. 5. The WakeLock interface

The WakeLock interface allows the page to request wake locks of a particular type, to determine the current wake lock state and to receive notifications when the wake lock state is changed.

[SecureContext, Exposed=Window] interface WakeLock : EventTarget {
  readonly attribute WakeLockType type;
  readonly attribute boolean active;
  attribute
  

  attribute EventHandler onactivechange;
  void request(optional WakeLockRequestOptions options);

};

type
Wake lock type associated with this WakeLock object.
active
Indicates whether wake lock of this type is currently acquired by the user agent .
onactivechange
Event handler with the corresponding event handler event type of activechange . Fired when current wake lock status indicated by the active attribute changes.

To create and initialize a WakeLock object of type type , the following steps MUST be performed:

  1. Create Let lock be a new WakeLock object in the Realm of this Navigator object and let wakeLock be that object.
  2. Set type attribute of wakeLock lock 's type to type .
  3. If the wake lock of type type is currently acquired , set active attribute of wakeLock lock 's active to true , otherwise to false .
  4. Return wakeLock . Instances of WakeLock are created with the internal slots described in the following table: Internal Slot Initial value Description ( non-normative ) [[RequestCounter]] 0 A number indicates the amount of current requests. A number greater than zero indicates an outstanding wake lock request The createRequest() method, when invoked, MUST run the following algorithm: Let request be a new WakeLockRequest object. Increase this . [[RequestCounter]] by one. Set request . [[OwnerWakeLock]] to this . Return request .
Note This additional WakeLockRequest object is added to address the issue with multiple components requesting wake lock on the same page independently.

5. 5.1 The WakeLockRequest WakeLockRequestOptions interface dictionary void

dictionary WakeLockRequestOptions {
  AbortSignal? signal;
};

Instances of The WakeLockRequest WakeLockRequestOptions.signal are created with the internal slots described in the following table: Internal Slot Initial value Description ( non-normative ) [[OwnerWakeLock]] null Set property allows to a WakeLock while initializing a new WakeLockRequest object. When the cancel() method is invoked, the following steps MUST be performed: If the cancel() method has already been invoked on this object, abort these steps. Let lock be this . [[OwnerWakeLock]] . Decrease lock . [[RequestCounter]] by one. 6. Managing Wake Locks This section applies to each wake lock type equally and independently, unless a particular wake lock type is explicitly mentioned. The user agent acquires the any wake lock by requesting the underlying operating system to apply the lock. The lock is considered acquired only when the request to the operating system succeeds. request.

Conversely, the user agent releases the wake lock by requesting the underlying operating system to no longer apply the wake lock. The lock is considered released only when the request to the operating system succeeds. When the user agent releases wake lock of type screen request() it method, when invoked, MUST reset the platform-specific inactivity timer after which the screen is actually turned off. Note Resetting the inactivity timer prevents the screen from going blank immediately after the wake lock is released. A Document is requesting the wake lock of type type if and only if run the following procedure returns true : algorithm:

  1. Let document options be this Document . the first argument.
  2. Let windowProxy signal be the WindowProxy object returned by document. defaultView . If windowProxy options is ’ dictionary member of the same name if present, or null , return false and abort these steps. otherwise.
  3. Let window record be the Window current settings object wrapped by windowProxy . 's associated wake lock state record .
  4. Let If navigator signal be the Navigator ’s aborted flag object returned by window.navigator . is set, abort these steps.
  5. Let If wakeLockResolution signal be is not null , then add the wake lock resolution following abort steps associated with to navigator and signal :
    1. Decrease type record . [[RequestCounter]] [ type ] by one.
    2. If wakeLockResolution record . [[RequestCounter]] [ type ] is either pending 0, then run the following steps in parallel :
      1. Run release a wake lock resolution or rejected wake lock resolution , return on false and abort these steps. this .
  6. If this 's type is " screen " and ", run the following steps:
    1. Let document be the responsible document of the current settings object .
    2. If document is hidden , return false and abort these steps.
  7. Increase record . [[RequestCounter]] [ type ] by one.
  8. If wakeLockResolution , which record . [[RequestCounter]] [ type ] is 1, run the following steps in parallel :
    1. Run Acquire a WakeLock object, has an outstanding wake lock request , return true , otherwise return on false this .
Note
The additional visibility requirement for screen wake lock is to prevent keeping the screen on when the page is not visible, such as when the browser is minimized. As this condition is transient and not under control of the web page, the specification chooses to automatically acquire and release the lock when visibility changes rather than having the page to deal with it, e.g by re-requesting the lock each time the page becomes visible again.

6. Managing Wake Locks

This section applies to each wake lock type equally and independently, unless a particular wake lock type is explicitly mentioned.

The user agent acquires the wake lock by requesting the underlying operating system to apply the lock. The lock is considered acquired only when the request to the operating system succeeds.

Conversely, the user agent releases the wake lock by requesting the underlying operating system to no longer apply the wake lock. The lock is considered released only when the request to the operating system succeeds.

The wake lock is applicable if the state of the operating system permits application of the lock (e.g. there is sufficient battery charge).

The screen wake lock MUST NOT be applicable after the screen is manually swiched off by the user until it is switched on again. Manually switching off the screen MUST NOT affect the applicability of the system wake lock .

Note
Whether the wake lock is applicable is a transient condition, e.g. when the battery charge is low but then the battery is recharged. So like the visibility requirement, this is part of automatic wake lock management and not part of the decision process whether to allow or deny the wake lock.
The user agent

6.1 Acquire wake lock algorithm MUST

To acquire the a wake lock for a given WakeLock of type object lock , run these steps in parallel :
  1. Let type when all of the following conditions become true: be lock 's type .
  2. The If the wake lock of for type type is not applicable . , return false .
  3. There is at least one Document that is requesting Ask the underlying operation system to acquire the wake lock of type type and let success be true if the operation succeeded, or else false .
  4. If success is different from lock 's active , set lock 's active to success and fire an event named "activechange" at lock .
  5. Return success .
The user agent MUST release the

6.2 Release wake lock algorithm when any of the conditions above become false. Whenever user agent acquires or releases

To release a wake lock, the user agent MUST perform the following steps lock for each a given WakeLock object: object lock , run these steps in parallel :
  1. If WakeLock object's Let type attribute is not equal to be lock 's type , abort these steps. .
  2. Queue a task which updates Ask the underlying operation system to release the wake lock of type type and let success be WakeLock true object's if the operation succeeded, or else false .
  3. If success is different from lock 's active attribute , set lock 's active to the negated success and fires fire an event named activechange "activechange" at the WakeLock object. lock .
  4. In the task described above, the
  5. If lock 's type is WakeLock "screen" run the following:
    1. The user agent objects's active attribute MUST be set to true if reset the wake lock has been acquired or to false if platform-specific inactivity timer after which the screen is actually turned off.
  6. Return success .
Note
Resetting the inactivity timer prevents the screen from going blank immediately after the wake lock has been is released.

7. Security and privacy considerations

Application of a wake lock causes various device components such as display or CPU to operate at higher power levels than they otherwise would. This can lead to undesirable and potentially dangerous effects such as excessive heating and faster than normal battery charge depletion. The latter is particularly relevant to mobile devices which may not have a stationary power source readily available. Complete battery depletion at an unexpected time can lead to inability of the user to make or receive calls and use network services, including the emergency call service. Implementations should consider preventing wake lock application if they determine that the remaining battery capacity is low.

The ability to observe the global state of a wake lock can create a communication channel between two otherwise isolated documents . One document can request wake lock which changes the global wake lock state, and another document can observe this change by subscribing to events in WakeLock .

When the user agent does not acquire wake lock even though a browsing context has requested it, this can be observed by the browsing context and can possibly disclose sensitive information about the state of the device such as that battery level is low.

8. Examples

This section is non-normative.

This example acquires a screen wake lock and releases it after a while:

async function tryKeepScreenAlive(minutes) {
  const lock = await navigator.getWakeLock("screen");
   request = lock.createRequest();

  setTimeout();

  const controller = new AbortController();
  const signal = controller.signal;
  lock.request({ signal });
  setTimeout(() => controller.abort(), minutes * 60 * 1000);

}
tryKeepScreenAlive(

10

);

This example requests a screen wake lock and listens to wake lock state changes:

request;
const controller = new AbortController();
const signal = controller.signal;
const checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
document.body.appendChild(checkbox);
navigator.getWakeLock("screen").then(lock => {
  lock.onactivechange = () => {
    checkbox.checked = lock.active;
  };
  request = lock.createRequest();

  lock.request({ signal });

});
setTimeout(


()

=>

request.cancel(),

controller.abort(),


5

*

1000

);

In this example, two screen wake lock requests are created and cancelled independently:

request1; request2;
const controller = new AbortController();
const signal = controller.signal;
const p1 = navigator.getWakeLock("screen");
const p2 = navigator.getWakeLock("screen");
p1.then( request1 = lock.createRequest());

p1.then(lock => lock.request({ signal }));

// ...somewhere else
p2.then( request2 = lock.createRequest());

p2.then(lock => lock.request({ signal }));

// ...somewhere else
 {
  request1.cancel();
  request2.cancel();
});

controller.abort();

9. Dependencies

The following concepts and interfaces are defined in [ HTML browsing context ]: , allowed to use Document defaultView Window WindowProxy Navigator queue a task event handler event handler event type in parallel The following concepts relevant settings object and interfaces active document are defined in [ WHATWG-DOM HTML ]: ].

fire an event The following concepts , AbortSignal , aborted flag , and interfaces add the following abort steps are defined in [ WEBIDL DOM ]: ].

"

AbortError , NotSupportedError " , DOMException , Secure context , SecurityError and available only in secure context are defined in [ WEBIDL ].

responsible document and current settings object are defined in [ HTML ].

set Promise , exists and internal slots empty are defined in [ ECMASCRIPT INFRA ].

The following concepts are defined in [ PROMISES-GUIDE ]: a promise rejected with a promise resolved with Promise reject promise and resolve promise internal slots The following concepts and interfaces are defined in [ ECMASCRIPT ]: ].

Realm

The following concepts and interfaces are defined in [ PAGE-VISIBILITY ]: Document's hidden attribute The following concepts and interfaces are is defined in [ FEATURE-POLICY PAGE-VISIBILITY ]:

policy-controlled feature , feature name , feature policy and default allowlist are defined in [ FEATURE-POLICY ]:

10. Use cases

This section is non-normative.

The use cases and requirements are documented in [ WAKE-LOCK-USE-CASES ].

11. 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 and MUST NOT are to be interpreted as described in [ RFC2119 ].

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

The user agent MUST implement the APIs defined in this specification in a manner that conforms to the ECMAScript Bindings defined in [ WEBIDL ].

A. IDL Index

enum WakeLockType { "screen", "system" };
partial interface Navigator {
  [SecureContext] Promise<WakeLock> getWakeLock(WakeLockType type);
};
[SecureContext, Exposed=Window] interface WakeLock : EventTarget {
  readonly attribute WakeLockType type;
  readonly attribute boolean active;
  attribute
  

  attribute EventHandler onactivechange;
  void request(optional WakeLockRequestOptions options);

};
  void

dictionary WakeLockRequestOptions {
  AbortSignal? signal;
};

B. Acknowledgments

This section is non-normative.

We would like to offer our sincere thanks to Mounir Lamouri, Sergey Konstantinov, Matvey Larionov, Dominique Hazael-Massieux (via the HTML5Apps project) for their contributions to this work.

C. References

C.1 Normative references

[DOM]
DOM Standard . Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/
[ECMASCRIPT]
ECMAScript Language Specification . Ecma International. URL: https://tc39.github.io/ecma262/
[FEATURE-POLICY]
Feature Policy . WICG. Living Standard. URL: https://wicg.github.io/feature-policy/
[HTML]
HTML Standard . Anne van Kesteren; Domenic Denicola; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[INFRA]
Infra Standard . Anne van Kesteren; Domenic Denicola. WHATWG. Living Standard. URL: https://infra.spec.whatwg.org/
[PAGE-VISIBILITY]
Page Visibility (Second Edition) . Jatinder Mann; Arvind Jain. W3C. 29 October 2013. W3C Recommendation. URL: https://www.w3.org/TR/page-visibility/ [PROMISES-GUIDE] Writing Promise-Using Specifications . Domenic Denicola. W3C. 16 February 2016. TAG Finding. URL: https://www.w3.org/2001/tag/doc/promises-guide
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels . S. Bradner. IETF. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[WEBIDL]
Web IDL . Cameron McCormack; Boris Zbarsky; Tobie Langel. W3C. 15 December 2016. W3C Editor's Draft. URL: https://heycam.github.io/webidl/ [WHATWG-DOM] DOM Standard . Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/

C.2 Informative references

[WAKE-LOCK-USE-CASES]
Wake Lock: Use cases . Marcos Caceres; Natasha Rooney; Dominique Hazaël-Massieux. W3C. 14 August 2014. W3C Note. URL: https://www.w3.org/TR/wake-lock-use-cases/