Sling Academy
Home/JavaScript/Keep Critical Info Visible Using JavaScript Wake Locks

Keep Critical Info Visible Using JavaScript Wake Locks

Last updated: December 13, 2024

In today's fast-paced, technology-driven world, ensuring that key information stays visible on your device screen can significantly boost user experience. Have you ever found yourself annoyed because your screen dimmed or turned off while following a particularly engaging recipe or workout video? Using JavaScript's Wake Lock API, you can prevent this from happening and keep critical information visible.

Understanding the Wake Lock API

The Wake Lock API is designed to prevent a device from going to sleep inadvertently. It enhances user engagement by ensuring that a web application remains in view longer than the standard screen timeout.

Types of Wake Locks

The Wake Lock API provides two primary types of locks:

  • Screen Wake Lock: This prevents the screen from dimming or turning off.
  • System Wake Lock: (Still experimental) Prevents the system from entering a sleep state, keeping the CPU active.

Installing and Using the Wake Lock API

As of now, the Wake Lock API is supported in most modern browsers, especially with respect to the screen wake lock feature.

Using the Screen Wake Lock

Let's look at how you can implement a screen wake lock to keep the display awake in JavaScript:

// Check if the Wake Lock API is supported
if ('wakeLock' in navigator) {
  let wakeLock;

  // Requesting a screen wake lock
  async function requestWakeLock() {
    try {
      wakeLock = await navigator.wakeLock.request('screen');
      console.log('Wake Lock is active');

      // Listen for release event
      wakeLock.addEventListener('release', () => {
        console.log('Wake Lock was released');
      });
    } catch (err) {
      console.error(`${err.name}, ${err.message}`);
    }
  }

  // Request a wake lock
  requestWakeLock();
}

In this example, we first check if the wakeLock property exists within the navigator object, delineating browser support. We then attempt to activate a screen wake lock using navigator.wakeLock.request('screen').

Handling Wake Lock Events

It's important to handle possible errors and user events correctly. A wake lock may be released unintentionally, for example, when minimizing the browser or when the tab loses focus. Implementing an event listener for such releases can ensure the app adapts accordingly.

Re-acquire Wake Lock on Page Visibility Change

// Re-acquire the wake lock on visibility change
function handleVisibilityChange() {
  if (document.visibilityState === 'visible' && wakeLock === null) {
    requestWakeLock();
  }
}

document.addEventListener('visibilitychange', handleVisibilityChange);

Here, we use the visibilitychange event to trigger requestWakeLock() whenever the page becomes visible again.

Practical Applications

Keeping critical info visible is essential for a variety of use cases:

  • Fitness Apps: Ensure instruction videos or statistics stay visible throughout workouts.
  • Recipe Sites: Prevent screen sleep when following a step-by-step recipe in the kitchen.
  • Educational Tools: Sustain focus on learning material without interruptions.

Best Practices

While using wake locks enhances user experience, it is crucial to:

  • Gain permission before requesting wake locks to respect user choice and battery life.
  • Release wake locks immediately when no longer needed.

By utilizing the Wake Lock API efficiently, developers can maintain a seamless, user-friendly interaction, making web applications more practical and engaging.

Next Article: Improve User Focus by Stopping Screen Dimming in JavaScript

Previous Article: Prevent Screen Sleep with the Screen Wake Lock API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration