Wake Lock
The Wake Lock API allows Web applications to prevent the resource such as the screen or system from becoming unavailable as long as the application holds a lock for that resource. The purpose of the API is to let the user or the application to complete the ongoing long activity - like navigation or reading - uninterrupted.
The initial implementation attempt that was experimentally available in some browsers was just a boolean flag controllable by the application. It was considered too open for abuse and too implicit.
More explicit approach is proposed as of mid-2019 and is available behind an "Experimental Web Platform Features" flag as well as via Origin Trial in Google Chrome. It allows to specify the resource on which the lock is requested, although currently only screen
option is available. The API also allows subscribing to the event when an external factor has interrupted the lock.
API glimpse
Newer specification
wakeLock = navigator.wakeLock.request('screen')
- Requests a wake lock on the resource specified, such as
screen
orsystem
. Returns aPromise
with the lock managing object. wakeLock.addEventListener('release', listener)
- An event fired when the lock has been released, possibly by external factor such as when user switched to another tab.
wakeLock.release()
- Manually releases the existing lock.
Older specification
screen.keepAwake = true
- The property allowing to acquire a screen wake lock when set to
true
and release it when set tofalse
.
Live Demo
Wake Lock status: unknown.
Supported API: none.
-
function printStatus(status) { document.getElementById("status").innerHTML = status; } let wakeLockObj = null; function toggle() { if ("keepAwake" in screen) { screen.keepAwake = !screen.keepAwake; printStatus(screen.keepAwake ? 'acquired' : 'not acquired'); } else if ("wakeLock" in navigator) { if (wakeLockObj) { wakeLockObj.release(); wakeLockObj = null; printStatus('released'); } else { printStatus('acquiring...'); navigator.wakeLock.request('screen') .then((wakeLock) => { wakeLockObj = wakeLock; wakeLockObj.addEventListener('release', () => { printStatus('released externally'); wakeLockObj = null; }) printStatus('acquired'); }) .catch((err) => { console.error(err); printStatus('failed to acquire: ' + err.message); }) } } } if ("keepAwake" in screen) { document.getElementById("api").innerHTML = 'screen.keepAwake'; printStatus('not acquired'); } else if ("wakeLock" in navigator) { document.getElementById("api").innerHTML = 'navigator.wakeLock'; printStatus('not acquired'); }
-
<p>Wake Lock status: <b id="status">unknown</b>.</p> <p>Supported API: <b id="api">none</b>.</p> <p><button onclick="toggle()">Toggle</button></p>