The Screen Wake Lock API can prevent a user’s computer screen from turning off so that they can work undisturbed.
If you’re a person who takes notes/hints from websites, then you may have experienced the screen getting dim or turned off if no action is performed for a while. The computer does this to save your battery, however it may feel irritating. If you’re a web developer and don’t want your customers to face this situation, you need to use JavaScript’s Screen Wake Lock API to keep the screen awake.
Check if your browser supports the Screen Wake Lock API by:
function isScreenLockSupported() {
return ('wakeLock' in navigator);
}
To enable screen lock, you will call,
navigator.wakeLock.request()
This will return a promise. Upon resolving the promise, you will get the WakeLockSentinel object:
let screenLock;
navigator.wakeLock.request('screen')
.then(lock => {
screenLock = lock;
});
// Or you can make an await call
let screenLock = await navigator.wakeLock.request('screen');
The WakeLockSentinel object contains the following three properties:
If a computer is in power save mode, has a low battery level, or if the tab is not visible, the Screen Wake Lock request may be rejected. Hence, it is always recommended to surround the request call with try...catch
, as shown below:
async function getScreenLock() {
if(isScreenLockSupported()){
let screenLock;
try {
screenLock = await navigator.wakeLock.request('screen');
} catch(err) {
console.log(err.name, err.message);
}
return screenLock;
}
}
To release the lock, you can call the release
method on the WakeLockSentinel object, as shown below:
function release() {
if(typeof screenLock !== "undefined" && screenLock != null) {
screenLock.release()
.then(() => {
console.log("Lock released 🎈");
screenLock = null;
});
}
}
let screenLock = await getScreenLock();
// If you want to release the lock you can call the release function.
// release();
The acquired locks will be automatically released when a document becomes inactive (e.g., tab change, window minimized, etc.). In this case, we need to acquire the lock again when the tab becomes visible. This can be handled using thevisibilitychange
event:
document.addEventListener('visibilitychange', async () => {
if (screenLock !== null && document.visibilityState === 'visible') {
screenLock = await navigator.wakeLock.request('screen');
}
});
The WakeLockSentinel object has an
screenLock.onrelease = () => {
console.log("Lock released 🎈");
};
// You can also use addEventListener
screenLock.addEventListener('release', () => {
console.log("Lock released 🎈");
});
Things to know
- The Screen Wake Lock API is only available when served over HTTPS.
- You can release the screen wake lock when the user ends an activity that required the always-on screen.