Wake Lock Sentinel Reacquires On Visible
Request a screen wake lock sentinel and re-acquire it on visibilitychange, because the browser releases the lock whenever the tab hides.
Code
// Screen Wake Lock: the sentinel is released automatically when the tab
// is hidden; a visibilitychange listener re-acquires it when visible again
let sentinel = null;
async function acquire() {
try {
sentinel = await navigator.wakeLock.request('screen');
console.log('wake lock acquired:', sentinel.type);
sentinel.addEventListener('release', () => {
console.log('wake lock released (tab hidden or release() called)');
sentinel = null;
});
} catch (err) {
console.log('wake lock denied:', err.name);
}
}
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && sentinel === null) {
acquire(); // re-acquire after the browser dropped it
}
});
acquire();
console.log('visibilityState:', document.visibilityState);How it works
The working surface is the function acquire — everything else is wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Watch out for
- The snippet leans on
document,navigator— browser-only surfaces a bare Node process cannot provide.
Using it
Entry signature: async function acquire()
The run emits 3 labeled sections — wake lock acquired:, wake lock denied:, visibilityState: — one per step.
Key statements
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && sentinel === null) {
acquire(); // re-acquire after the browser dropped it
}
});
sentinel.addEventListener('release', () => {
console.log('wake lock released (tab hidden or release() called)');
sentinel = null;
});
sentinel = await navigator.wakeLock.request('screen');
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Does Wake Lock Sentinel Reacquires On Visible run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.