How to Keep Mobile Screens Awake with JavaScript Wake Lock API
This guide explains how to use the modern Wake Lock Web API in JavaScript to prevent a mobile screen from sleeping, covering feature detection, requesting and releasing the lock, handling release events, and automatically reacquiring the lock when the page becomes visible again.
When building H5 applications that require the device screen to stay on, the Wake Lock Web API—available since Chrome 85—offers a native way to prevent the screen from dimming or locking. Safari does not yet support it, so a polyfill can be used on iOS until support arrives.
Understanding Wake Lock
The Wake Lock API can keep the screen from turning off, dimming, or locking, but it only works while the tab or window is active. It also provides a method to manually release the lock.
Checking for Support
const canWakeLock = () => 'wakeLock' in navigator;Requesting a Wake Lock
let wakeLock = null;
const requestWakeLock = async () => {
try {
wakeLock = await navigator.wakeLock.request('screen');
console.log('Wake Lock is active!');
} catch (err) {
console.log(`${err.name}, ${err.message}`);
}
};
requestWakeLock();Releasing the Wake Lock
wakeLock.release().then(() => wakeLock = null);Listening for Release Events
wakeLock.addEventListener('release', () => {
console.log('Wake Lock has been released');
});Re‑acquiring on Visibility Change
document.addEventListener('visibilitychange', async () => {
if (wakeLock !== null && document.visibilityState === 'visible') {
requestWakeLock();
}
});Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
JavaScript
Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
