Screen Wake Lock API

W3C Working Draft

This version:
https://www.w3.org/TR/2020/WD-screen-wake-lock-20200929/
Latest published version:
https://www.w3.org/TR/screen-wake-lock/
Latest editor's draft:
https://w3c.github.io/screen-wake-lock/
Test suite:
https://w3c-test.org/screen-wake-lock/
Implementation report:
https://www.w3.org/wiki/DAS/Implementations
Previous version:
https://www.w3.org/TR/2017/CR-wake-lock-20171214/
Editors:
Kenneth Rohde Christiansen (Intel Corporation)
Marcos Cáceres (W3C Invited Expert)
Raphael Kubo da Costa (Intel Corporation)
Former editors:
Ilya Bogdanovich (Yandex)
Andrey Logvinov (Yandex)
Participate:
GitHub w3c/screen-wake-lock
File a bug
Commit history
Pull requests
Quality Assurance Lead:
Wanming Lin (Intel)

Abstract

This document specifies an API that allows web applications to request a screen wake lock. Under the right conditions, and if allowed, the screen wake lock prevents the system from turning off a device's screen.

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 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 Devices and Sensors Working Group as a Working Draft. This document is intended to become a W3C Recommendation.

GitHub Issues are preferred for discussion of this specification.

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 1 August 2017 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 15 September 2020 W3C Process Document.

1. Introduction

This section is non-normative.

Modern operating systems 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, limiting power usage as much as possible.

Though this is great for prolonged battery life, it can sometime hinder some use cases such as scanning a barcode, reading an ebook, following a recipe, presenting to an audience, and so on. See also Wake Lock: Use cases.

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.

2. Wake Locks

This specification defines the following wake lock type:

  1. A screen wake lock prevents the screen from turning off. Only visible documents can acquire the screen wake lock.

In the API, the wake lock types are represented by the WakeLockType enum values.

Note

Other specifications might define different wake lock types.

3. Policy control

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

Note

4. Permissions and user prompts

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

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

It is RECOMMENDED that a user agent show 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.

4.1 The "screen-wake-lock" powerful feature

The "screen-wake-lock" powerful feature enables the capability defined by this specification.

4.2 Permission algorithms

To block a permission, run these steps:

  1. Let document be the responsible document of the current settings object.
  2. Let descriptor be an instance of PermissionDescriptor.
  3. Set descriptor's permission state to "denied".
  4. Let name be descriptor's name member.
  5. Let record be the platform wake lock's state record associated with document and name.
  6. For each lock in record.[[ActiveLocks]]:
    1. Run release a wake lock with lock and name.

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

  1. Let permissionDesc be a newly created PermissionDescriptor.
  2. Set permissionDesc's name member to "screen-wake-lock".
  3. Let resultPromise be the result of running query a permission with permissionDesc.
  4. Await resultPromise to settle.
  5. If resultPromise rejects, return "denied".
  6. Otherwise, let status be the result of resultPromise.
  7. Let state be the value of status.state.
  8. If state is not "prompt", return state.
  9. If the current global object does not have transient activation, return "denied".
  10. Otherwise, return the result of requesting permission to use with permissionDesc.

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 per responsible document with the following internal slots:

Internal slot Initial value Description (non-normative)
[[ActiveLocks]] The empty list. A list of WakeLockSentinel objects, representing active wake locks associated with the responsible document.

6. Extensions to the Navigator interface

WebIDL[SecureContext]
partial interface Navigator {
  [SameObject] readonly attribute WakeLock wakeLock;
};

7. The WakeLock interface

The WakeLock interface allows a document to acquire a screen wake lock.

WebIDL[SecureContext, Exposed=(Window)]
interface WakeLock {
  Promise<WakeLockSentinel> request(WakeLockType type);
};

7.1 The request() method

The request() method, when invoked, MUST run the following steps. The method takes one argument, the WakeLockType type:

  1. Let document be the responsible document of the current settings object.
    1. If document is not allowed to use the policy-controlled feature named "screen-wake-lock", return a promise rejected with a "NotAllowedError" DOMException.
    2. If the user agent denies the wake lock of this type for document, return a promise rejected with "NotAllowedError" DOMException.
  2. If the document's browsing context is null, return a promise rejected with "NotAllowedError" DOMException.
  3. If document is not fully active, return a promise rejected with with a "NotAllowedError" DOMException.
  4. If document is hidden, return a promise rejected with "NotAllowedError" DOMException.
  5. Let promise be a new promise.
  6. Return promise and run the following steps in parallel:
    1. Abort when document is hidden.
    2. Let state be the result of awaiting obtain permission steps with "screen-wake-lock":
      1. If state is "denied", then reject promise with a "NotAllowedError" DOMException, and abort these steps.
    3. Let lock be a new WakeLockSentinel object with its type attribute set to type.
    4. Invoke acquire a wake lock with lock and "screen".
      Note
    5. Resolve promise with lock.
  7. If aborted, reject promise with a "NotAllowedError" DOMException.

8. The WakeLockSentinel interface

WebIDL[SecureContext, Exposed=(Window)]
interface WakeLockSentinel : EventTarget {
  readonly attribute boolean released;
  readonly attribute WakeLockType type;
  Promise<undefined> release();
  attribute EventHandler onrelease;
};

A WakeLockSentinel object provides a handle to a platform wake lock, and it holds on to it until it is either manually released or until the underlying platform wake lock is released. Its existence keeps a platform wake lock for a given wake lock type active, and releasing all WakeLockSentinel instances of a given wake lock type will cause the underlying platform wake lock to be released.

Note

8.1 Internal slots

WakeLockSentinel instances are created with the following internal slots:

Internal slot Initial value Description (non-normative)
[[Released]] false Whether the given WakeLockSentinel has been released.

8.2 The released attribute

The released attribute's getter returns the value of the [[Released]] internal slot.

Note

8.3 The type attribute

The type attribute corresponds to the WakeLockSentinel's wake lock type.

8.4 The release() method

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

  1. If this object's [[Released]] internal slot is true, return a promise resolved with undefined.
  2. Otherwise, let promise be a new promise.
  3. Run the following steps in parallel:
    1. Run release a wake lock with lock set to this object and type set to the value of this object's type attribute.
    2. Resolve promise.
  4. Return promise.

8.5 The onrelease attribute

The onrelease attribute is an event handler whose corresponding event handler event type is release.

It is used to notify scripts that a given WakeLockSentinel object's handle has been released, either due to the release() method being called or because the wake lock was released by the user agent.

Note
Note

9. The WakeLockType enum

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

WebIDLenum WakeLockType { "screen" };
screen
Screen wake lock type.

10. 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. A possible return value of the request to the underlying operating system is not checked. In other words, user agents MUST treat wake lock acquisition as advisory-only.

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.

Note

10.1 Auto-releasing wake locks

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

10.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 document be the responsible document of the current settings object.
  2. Let screenRecord be the platform wake lock's state record associated with document and wake lock type screen wake lock.
  3. For each lock in screenRecord.[[ActiveLocks]]:
    1. Run release a wake lock with lock and "screen".
Note

10.3 Handling document loss of visibility

When the user agent determines that the visibility state of the responsible document of the current settings object changes, it must run these steps:

  1. Let document be the responsible document of the current settings object.
  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 wake lock.
  4. For each lock in screenRecord.[[ActiveLocks]]:
    1. Run release a wake lock with lock and "screen".
Note

10.4 Acquire wake lock algorithm

To acquire a wake lock for a given lock and type, run these steps in parallel:

  1. If the wake lock for type type is not applicable, return false.
  2. If the platform wake lock has an active lock for type, abort these steps.
  3. Ask the underlying operating system to acquire the wake lock of type type.
  4. Let document be the responsible document of the current settings object.
  5. Let record be the platform wake lock's state record associated with document and type.
  6. Add lock to record.[[ActiveLocks]].

10.5 Release wake lock algorithm

To release a wake lock for a given lock and type, run these steps in parallel:

  1. Let document be the responsible document of the current settings object.
  2. Let record be the platform wake lock's state record associated with document and type.
  3. If record.[[ActiveLocks]] does not contain lock, abort these steps.
  4. Remove lock from record.[[ActiveLocks]].
  5. If the internal slot [[ActiveLocks]] of all the platform wake lock's state records are all empty, then run the following steps in parallel:
    1. Ask the underlying operating 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 type is "screen" run the following:
      1. Reset the platform-specific inactivity timer after which the screen is actually turned off.
      Note
  6. Queue a task to run the following steps:
    1. Set lock's [[Released]] internal slot to true.
    2. Fire an event named "release" at lock.

11. Security and privacy considerations

Wake locks can cause various device components such as display or CPU to operate at higher power levels than they otherwise would. This can lead to undesirable effects such as faster than normal battery charge depletion. This 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 MAY ignore requests for screen wake lock if, for example, the battery capacity is low, or the user has put their device in a power-saving mode.

12. Examples

This section is non-normative.

Example 1: Acquires and releases a screen wake lock
function tryKeepScreenAlive(minutes) {
  navigator.wakeLock.request("screen").then(lock => {
    setTimeout(() => lock.release(), 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 sentinel = await navigator.wakeLock.request("screen");
checkbox.checked = !sentinel.released;
sentinel.onrelease = () => checkbox.checked = !sentinel.released;

In this example, two different wake lock requests are created and released independently:

let lock1 = await navigator.wakeLock.request("screen");
let lock2 = await navigator.wakeLock.request("screen");

lock1.release();
lock2.release();

13. Dependencies

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

14. 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 MAY, MUST, MUST NOT, and RECOMMENDED in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.

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

A. IDL Index

WebIDL[SecureContext]
partial interface Navigator {
  [SameObject] readonly attribute WakeLock wakeLock;
};

[SecureContext, Exposed=(Window)]
interface WakeLock {
  Promise<WakeLockSentinel> request(WakeLockType type);
};

[SecureContext, Exposed=(Window)]
interface WakeLockSentinel : EventTarget {
  readonly attribute boolean released;
  readonly attribute WakeLockType type;
  Promise<undefined> release();
  attribute EventHandler onrelease;
};

enum WakeLockType { "screen" };

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, Raphael Kubo da Costa for their contributions to this work.

C. Changes

This section is non-normative.

This section documents the changes since previous publications.

C.1 Changes since the 14 December 2017 CR

D. References

D.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.es/ecma262/
[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/
[PERMISSIONS]
Permissions. Mounir Lamouri; Marcos Caceres; Jeffrey Yasskin. W3C. 20 July 2020. W3C Working Draft. URL: https://www.w3.org/TR/permissions/
[PERMISSIONS-POLICY]
Permissions Policy. Ian Clelland. W3C. 16 July 2020. W3C Working Draft. URL: https://www.w3.org/TR/permissions-policy-1/
[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
[RFC8174]
Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL: https://tools.ietf.org/html/rfc8174
[WebIDL]
Web IDL. Boris Zbarsky. W3C. 15 December 2016. W3C Editor's Draft. URL: https://heycam.github.io/webidl/

D.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/