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)
Implementation status:
Chrome

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 March 2019 W3C Process Document .

1. Introduction

Modern OSs achieve longer battery life by implementing aggressive power management, meaning that shortly after the lack of user activity, a host device may lower the screen brightness, turn the screen off and even let the CPU go into a deep power state, allowing to sip as little power as possible.

Though this is great for prolonged battery life, it can sometime hinder good, valid use-cases such as:

More use-cases can be found in Use Cases and Requirements .

A wake lock will generally prevent something from happening, but UAs (and the underlying OS) may time limit a wake lock given the battery status (wall power connected, discharging, low battery level), or even disallow wake locks in the case a power saving mode is activated.

Any active wake lock MUST also prevent the page from entering UA induced CPU suspension as defined by [ PAGE-LIFECYCLE ].

This specification defines the following wake lock types :

  1. A screen wake lock prevents the screen from turning off. Only visible documents can acquire the wake lock.
  2. A system wake lock prevents the CPU from entering a deep power state. This may also prevent communication chips such as cellular or Wi-Fi from sleeping.
Note
Note

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

2. Policy control

The Wake Lock API defines a policy-controlled feature identified by the string "wake-lock" . Its default allowlist is ["self"] .

Note

3. Permissions and user prompts

The [ PERMISSIONS ] API provides a uniform way for websites to request permissions from users and query which permissions they have.

It is recommended that a UA shows some form of unobtrusive notification that informs the user when a wake lock is active, as well as provides the user with the means to block the ongoing operation, or simply dismiss the notification.

3.1 The WakeLockPermissionDescriptor dictionary

The "wake-lock" powerful feature is defined as follows:

The permission descriptor type is represented by the WakeLockPermissionDescriptor dictionary , which extends the PermissionDescriptor with a type member, allowing for more fine-grained permissions.

dictionary WakeLockPermissionDescriptor : PermissionDescriptor {
  WakeLockType type;
};

The PermissionDescriptor . name is "wake-lock" .

3.2 Permission algorithms

To block a permission , run these steps:

  1. Let descriptor be an instance of WakeLockPermissionDescriptor .
  2. Set descriptor 's permission state to " denied " .
  3. Let record be the platform wake lock 's state record associated with descriptor 's type member.
  4. For each lock in record . [[ InstanceList ]] :
    1. Run release a wake lock on lock .

To obtain permission for wake lock type type , run these steps in parallel . This async algorithm returns either " granted " or " denied " .

  1. Let permissionDesc be a newly created WakeLockPermissionDescriptor .
  2. Set permissionDesc 's name member to " wake-lock ".
  3. Set permissionDesc 's type to type .
  4. Let resultPromise be the result of running query a permission with permissionDesc .
  5. Await resultPromise to settle.
  6. If resultPromise rejects, return " denied " .
  7. Otherwise, let status be the result of resultPromise .
  8. Let state be the value of status . state .
  9. If state is " prompt " , run the following steps:
    1. If these obtain permission steps were not triggered by user activation , return " denied " .
    2. Return the result of requesting permission to use with permissionDesc .
  10. Otherwise, return state .
Note

4. 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.

5. Concepts and state record

The term platform wake lock refers to platform interfaces with which the user agent interacts to query state and acquire and release a wake lock.

A platform wake lock can be defined by the underlying platform (e.g. in a native wake lock framework) or by the user agent, if it has direct hardware control.

Each platform wake lock (one per wake lock type ) has an associated state record with the following internal slots :

Internal slot Initial value Description ( non-normative )
[[InstanceList]] The empty ordered set . A ordered set of WakeLock instances.
[[RequestCounter]] 0. The value indicates the amount of current requests for the wake lock type .

6. 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.

[Constructor(WakeLockType type), SecureContext, Exposed=(DedicatedWorker, Window)]
interface WakeLock : EventTarget {
  [Exposed=Window] static Promise<PermissionState> requestPermission(WakeLockType type);
  readonly attribute WakeLockType type;
  readonly attribute boolean active;
  attribute EventHandler onactivechange;
  Promise<void> request(optional WakeLockRequestOptions options);
};

6.1 Internal slots

Internal slot Description ( non-normative )
[[requestPromise]] The pending promise created during request() .

6.2 Constructor

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

  1. Let document be the responsible document of the current settings object .
  2. If the current global object is the DedicatedWorkerGlobalScope object and its owner set is empty , throw a " NotAllowedError " DOMException .
  3. If the current global object is the Window object and the document 's browsing context is null , throw a " NotAllowedError " DOMException .
  4. If document is not allowed to use the policy-controlled feature named " wake-lock ", throw a " NotAllowedError " DOMException .
  5. If the user agent denies the wake lock of this type for document , throw a " NotAllowedError " DOMException .
  6. Let lock be a new WakeLock object.
  7. Set lock 's type to type .
  8. Let record be the platform wake lock 's state record associated with type .
  9. Add lock to record . [[ InstanceList ]] .
  10. If the wake lock of type type is currently acquired , set lock 's active to true , otherwise to false .
  11. Return lock .

6.3 requestPermission() static method

The requestPermission( type ) method, when invoked, MUST run the following steps. This algorithm resolves with either " granted " or " denied " .

  1. Let promise be a new promise .
  2. Return promise and run the following steps in parallel :
    1. Let state be the result of running and waiting for the obtain permission steps with type .
    2. Resolve promise with state .

6.4 type attribute

When getting, the type attribute returns this WakeLock 's wake lock type .

6.5 active attribute

The active attribute represents whether a wake lock is currently acquired by the WakeLock instance.

6.6 onactivechange attribute

A WakeLock 's onactivechange attribute is an EventHandler with the corresponding event handler event type of activechange . Fired when current wake lock status indicated by the active attribute changes.

6.7 The WakeLockRequestOptions dictionary

dictionary WakeLockRequestOptions {
  AbortSignal?

  AbortSignal? signal;

};

The signal member is used to abort the wake lock request.

6.8 request() method

To abort the request steps for a running instance of request() , run these additional steps:

  1. Set lock . [[ requestPromise ]] to undefined .
  2. Abort the associated request() algorithm.

The request() method, when invoked, MUST run the following steps:

  1. Let options be the first argument.
  2. Let lock be the context object .
  3. Let promise be a new promise .
  4. If lock . [[ requestPromise ]] is not undefined , reject promise with a " InvalidStateError " DOMException , and run abort the request steps .
  5. If options . signal ’s aborted flag is set, then reject promise with an " AbortError " DOMException , and run abort the request steps .
  6. If options . signal is not null , then add to options . signal :
    1. Run release a wake lock on lock .
  7. Set lock . [[ requestPromise ]] to promise.
  8. Return promise and run the following steps in parallel :
    1. Let state be the result of running and waiting for the obtain permission steps with lock . type .
    2. If state is " denied " , then reject promise with a " NotAllowedError " DOMException , and run abort the request steps .
    3. If the current global object is not a DedicatedWorkerGlobalScope object, run the following steps:
      1. Let document be the responsible document of the current settings object .
      2. If document is not fully active , reject promise with a " NotAllowedError " DOMException , and run abort the request steps .
      3. If lock 's type is " screen " and the Document of the top-level browsing context is hidden , reject promise with a " NotAllowedError " DOMException , and run abort the request steps .
    4. Let success be the result of awaiting acquire a wake lock on lock .
    5. If success is false then reject promise with a " NotAllowedError " DOMException , and run abort the request steps .
    6. Resolve promise with void .
Note

7. 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 switched 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

7.1 Auto-releasing wake locks

A user agent may release a wake lock at any time it:

7.2 Handling document loss of full activity

When the user agent determines that a responsible document of the current settings object is no longer fully active , it must run these steps:

  1. Let record be the platform wake lock 's state record associated with wake lock type " screen " and " system " .
  2. For each lock in record . [[ InstanceList ]] :
    1. Run release a wake lock on lock .
Note

7.3 Handling document loss of visibility

When the user agent determines that the visibility state of the Document of the top-level browsing context changes, it must run these steps:

  1. Let document be the Document of the top-level browsing context .
  2. If document 's visibility state is "visible" , abort these steps.
  3. Let screenRecord be the platform wake lock 's state record associated with wake lock type " screen " .
  4. For each lock in screenRecord . [[ InstanceList ]] :
    1. Run release a wake lock on lock .
Note
Note

7.4 Acquire wake lock algorithm

To acquire a wake lock for a given WakeLock object lock , run these steps in parallel :
  1. Let type be lock 's type .
  2. Let record be the platform wake lock 's state record associated with type .
  3. If the wake lock for type type is not applicable , return false .
  4. Set active to true if the platform wake lock has an active wake lock for type .
  5. Otherwise, ask the underlying operation system to acquire the wake lock of type type and set active to true if the operation succeeded, or else false .
  6. Increment record . [[RequestCounter]] by one.
  7. If active is different from lock 's active , set lock 's active to active and fire an event named "activechange" at lock .
  8. Return active .

7.5 Release wake lock algorithm

To release a wake lock for a given WakeLock object lock , run these steps in parallel :

  1. Let type be lock 's type .
  2. Let record be the platform wake lock 's state record associated with type .
  3. If the promise lock . [[ requestPromise ]] not undefined and is pending, reject it with an " AbortError " DOMException and abort the request steps for the associated running request() algorithm.
  4. Decrement record . [[RequestCounter]] by one.
  5. If record . [[RequestCounter]] is 0, then run the following steps in parallel :
    1. Ask the underlying operation system to release the wake lock of type type and let success be true if the operation succeeded, or else false .
    2. If success is true and lock 's type is "screen" run the following:
      1. Reset the platform-specific inactivity timer after which the screen is actually turned off.
  6. Set active to false .
  7. If active is different from lock 's active , set lock 's active to active and fire an event named "activechange" at lock .
Note

8. 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 Document objects. 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.

9. Examples

This section is non-normative.

Example 1 : Acquires and releases a screen wake lock
function tryKeepScreenAlive(minutes) {
  const controller = new AbortController();
  const signal = controller.signal;
  const lock = new WakeLock("screen");
  lock.request({ signal });
  setTimeout(() => controller.abort(), minutes * 60 * 1000);
}
tryKeepScreenAlive(

10

);

This example allows the user to request a screen wake lock by clicking on a checkbox, but updates the checkbox checked state in case the wake lock state changes:

const checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
document.body.appendChild(checkbox);
const lock = new WakeLock("screen");
lock.onactivechange = () => checkbox.checked = lock.active;
const controller = new AbortController();
try {
  checkbox.disabled = true;
  if (checkbox.checked) {
    await lock.request({ signal: controller.signal });
  } else {
    controller.abort();
  }
} catch {
  // On failure, reset the checkbox to reflect the
  // current state. `onactivechanged` will not have fired.
  checkbox.checked = lock.active;
} finally {
  checkbox.disabled = false;
}

In this example, two different wake lock requests are created and released together using an AbortController :

const screen = new WakeLock("screen");
const system = new WakeLock("system");
const controller = new AbortController();
const signal = controller.signal;
screen.request({ signal });
system.request({ signal });
controller.abort();

10. Dependencies

Document's hidden attribute, and visibility state are defined in [ PAGE-VISIBILITY ].

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.

A. IDL Index

dictionary WakeLockPermissionDescriptor : PermissionDescriptor {
  WakeLockType type;
};
enum WakeLockType { "screen", "system" };
[Constructor(WakeLockType type), SecureContext, Exposed=(DedicatedWorker, Window)]
interface WakeLock : EventTarget {
  [Exposed=Window] static Promise<PermissionState> requestPermission(WakeLockType type);
  readonly attribute WakeLockType type;
  readonly attribute boolean active;
  attribute EventHandler onactivechange;
  Promise<void> request(optional WakeLockRequestOptions options);
};
dictionary WakeLockRequestOptions {
  AbortSignal?

  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, Domenic Denicola, Thomas Steiner 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 . Ian Clelland. W3C. 16 April 2019. W3C Working Draft. URL: https://www.w3.org/TR/feature-policy-1/
[fetch]
Fetch Standard . Anne van Kesteren. WHATWG. Living Standard. URL: https://fetch.spec.whatwg.org/
[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-LIFECYCLE]
Page Lifecycle . WICG. Living Standard. URL: https://wicg.github.io/page-lifecycle/spec.html
[PAGE-VISIBILITY]
Page Visibility (Second Edition) . Jatinder Mann; Arvind Jain. W3C. 29 October 2013. W3C Recommendation. URL: https://www.w3.org/TR/page-visibility/
[PERMISSIONS]
Permissions . Mounir Lamouri; Marcos Caceres; Jeffrey Yasskin. W3C. 25 September 2017. W3C Working Draft. URL: https://www.w3.org/TR/permissions/
[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 . Boris Zbarsky. W3C. 15 December 2016. W3C Editor's Draft. URL: https://heycam.github.io/webidl/

C.2 Informative references

[BACKGROUND-FETCH]
Background Fetch . WICG. Living Standard. URL: https://wicg.github.io/background-fetch/