Some new features in JavaScript are great to see, and the wake lock API is one of those. It allows us to interact with the host system and can help the developer instruct the operating system to keep the screen awake using JavaScript!
This can be particularly useful for cases where you want the user’s device to not get locked due to inactivity timeouts. It can be useful for the browser to instruct the operating system that the user is engaging in an activity, such as recording something or watching a video.
The Wake lock API can then be used to prevent the screen from sleeping or being dimmed. For requesting the permission:
let screenLock;
try {
screenLock = await navigator.wakeLock.request('screen');
} catch (err) {
console.log('Error with wake lock: ', err);
}
JavaScriptIf the request succeeds, the host machine will not sleep until the wake lock gets programmatically released. And that is pretty much all that is needed to keep the screen awake using JavaScript.
We wrap the code in a try-catch because the Screen Wake Lock request can be rejected if the host device is in power saver mode, or has a low battery, or the current tab is not visible.
For releasing the wake lock:
await screenLock.release()
JavaScriptIt is also worth noting that the lock gets released automatically if the document becomes inactive (user changes tabs/windows etc.). To handle this, we could add a visibilitychange
event:
document.addEventListener('visibilitychange', async () => {
try {
screenLock = await navigator.wakeLock.request('screen');
} catch (err) {
console.log('Error with wake lock: ', err);
}
});
JavaScriptNote:
A couple of things to keep in mind:
This is a great feature to use on devices to ensure that the device does not go to sleep.
I am terrible at optimizing my keyboard layout for anything. But off lately, my little…
I recently switched completely to the Brave browser and have set ad blocking to aggressive…
I was preparing a slide deck for a hackathon and decided to put in a…
I have been using npx a lot lately, especially whenever I want to use a…
Manually copy-pasting the output of a terminal command with a mouse/trackpad feels tedious. It is…
While working on a project, I wanted to do an integrity check of a file…