Published on

Avoid Screen Dimming or Locking with Screen Wake Lock API in Browser

Authors

Most of the devices come with screen dimming + locking feature that helps to optimize the battery consumption when it's not in use.

However, there could be a cause when it messes up with your use cases. For example, let's say you have built a web-based timer app that you use on your devices.

You just load that app, set the time and let the timer run on one of your devices and do work on another.

In such cases, you ALWAYS want the screen to be active and don't want it to dim or lock automatically either.

That's where Screen Wake Lock API comes in.

Locking the screen

let wakeLock = null;

const requestWakeLock = async () => {
  try {
    wakeLock = await navigator.wakeLock.request();
    wakeLock.addEventListener('release', () => {
      console.log('Screen Wake Lock released:', wakeLock.released);
    });
    console.log('Screen Wake Lock released:', wakeLock.released);
  } catch (err) {
    console.error(`${err.name}, ${err.message}`);
  }
};

await requestWakeLock()

Releasing the screen

You can also release it manually like this

let wakeLock = null;
// wakeLock will be initialized with requestWakeLock. Refer above snippet
wakeLock.release();

By default if you switch to different tab then it'll be automatically released. And you watch for page visibility and then request lock again like this

const handleVisibilityChange = async () => {
  if (wakeLock !== null && document.visibilityState === 'visible') {
    await requestWakeLock();
  }
};

document.addEventListener('visibilitychange', handleVisibilityChange);

Heads up

  • Screen Wake Lock API works only on HTTPS

  • Currently, it is primarily supported only in Chromium-based browsers

Reference

Happy active screen!