brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: navigator.wakeLock keeps the screen on for a recipe or a timer

Javascript
~/tips/tip-js-wake-lock-keep-screen-on

let lock = null;

Stop a phone from dimming while someone follows steps on your page.

Following a recipe on a phone means poking the screen with flour on your fingers so it does not lock. The Screen Wake Lock API lets a page ask the device to stay awake.

let lock = null;

async function keepAwake() {
  try {
    lock = await navigator.wakeLock.request("screen");
    lock.addEventListener("release", () => { lock = null; });
  } catch (err) {
    console.warn("Wake lock refused:", err.name);
  }
}

document.addEventListener("visibilitychange", () => {
  if (lock === null && document.visibilityState === "visible") keepAwake();
});

request("screen") returns a sentinel object while the lock is active. Call lock.release() when the user is done, for example when they leave cooking mode.

The browser drops the lock by itself when the tab is hidden or the window is minimized. That is why the example asks again on visibilitychange; without that, the screen keeps dimming after the first time the user switches apps. A real page would also check a “cooking mode” flag here, so it only asks when the user wanted it.

The request can be refused, for example when the battery is low or power saving is on, so always handle the error and never assume it worked. It also needs HTTPS.

Support: Chrome 84, Firefox 126, Safari 16.4 on the Mac and 18.4 on iPhone according to MDN. I’d put it behind a toggle the user switches on, since keeping a screen awake drains the battery.

Further reading: MDN: Screen Wake Lock API, MDN: WakeLock.request()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link