DEV Community

Cover image for Stay Alive Using the Wake Lock API in Next.js
Titus Efferian
Titus Efferian

Posted on

Stay Alive Using the Wake Lock API in Next.js

If we want to prevent our devices from going into a dim or sleep state, we can configure those settings from our screen options, depending on the OS we are using.

But how can we keep our screen always active using JavaScript? We can use the WakeLock API.

I am going to provide a simple explanation on how to implement the WakeLock API using the latest version of Next.js.

What is WakeLock?

WakeLock API provides a way to prevent devices from dimming or locking the screen when an application needs to keep running.

Implementation

Let’s try implementing the WakeLock API in Next.js. We are going to create a button that, when clicked, calls the WakeLock API and handles enabling and disabling the WakeLock.

Let's prepare the state to handle some enable/disable logic and to store the WakeLockSentinel.

  const [{ isWakeLocked, wakelock }, setWakeLock] = useState<{
    isWakeLocked: boolean;
    wakelock: WakeLockSentinel | null;
  }>({
    isWakeLocked: false,
    wakelock: null,
  });
Enter fullscreen mode Exit fullscreen mode

Here, we aim to handle:

  • Feature detection: Only manage this onClick event for web browsers that already support the WakeLock API.
  • Release WakeLock: Handle disabling the WakeLock.
  • Enable WakeLock: Activate the WakeLock and store the WakeLockSentinel in the state.
const handleOnClick = useCallback(async () => {
  // feature detection
  if ("wakeLock" in navigator === false) {
    modals.openConfirmModal({
      title: "Wake lock not supported",
      children: <Text>Your browser does not support Wake Lock API.</Text>,
      labels: {
        cancel: "Close",
        confirm: "Ok",
      },
    });
    return;
  }
  // disable wakelock
  if (isWakeLocked) {
    wakelock?.release();
    setWakeLock((prev) => {
      return {
        ...prev,
        isWakeLocked: false,
      };
    });
    return;
  }
  // enable wakelock
  const temp = await navigator.wakeLock.request("screen");
  setWakeLock((prev) => {
    return {
      ...prev,
      isWakeLocked: true,
      wakelock: temp,
    };
  });
}, [isWakeLocked, wakelock]);
Enter fullscreen mode Exit fullscreen mode
<Button
  size="xl"
  className={classes.control}
  variant="gradient"
  gradient={{
    from: isWakeLocked ? "red" : "blue",
    to: isWakeLocked ? "pink" : "cyan",
  }}
  onClick={handleOnClick}
>
  {isWakeLocked ? "Disable Wake Lock" : "Enable Wake Lock"}
</Button>;
Enter fullscreen mode Exit fullscreen mode

Final Result

Final Result

Resources

Top comments (0)