The Screen Wake Lock API provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.
How to request & release screen wake lock programmatically?
Let's follow the code below:
index.html
<!--
Wake Lock Example
-----------------------------------
The Screen Wake Lock API provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.
-----------------------------------
Reference :
- https://developer.mozilla.org/en-US/docs/Web/API/Screen_Wake_Lock_API
-->
<html>
<head>
<title>Wake Lock Example</title>
</head>
<body>
<h1>Wake Lock Example</h1>
<button onclick="requestWakeLock()">Request WakeLock</button>
<button onclick="releaseWakeLock()">Release WakeLock</button>
</body>
</html>
<script type="text/javascript">
if ('wakeLock' in navigator) {
console.log('Screen Wake Lock API supported!');
}
else {
console.log('Wake lock is not supported by this browser.');
}
// Create a reference for the Wake Lock.
let wakeLock = null;
async function requestWakeLock() {
// create an async function to request a wake lock
try {
wakeLock = await navigator.wakeLock.request('screen');
console.log('Wake Lock is active!');
wakeLock.addEventListener('release', () => {
// the wake lock has been released
console.log('Wake Lock has been released');
});
}
catch (e) {
// The Wake Lock request has failed - usually system related, such as battery.
console.log(`${e.name}, ${e.message}`);
}
}
function releaseWakeLock() {
if(wakeLock !== null && wakeLock !== undefined) {
wakeLock.release().then(() => {
wakeLock = null;
});
}
}
</script>
Reference :