Sling Academy
Home/JavaScript/Prevent Screen Sleep with the Screen Wake Lock API in JavaScript

Prevent Screen Sleep with the Screen Wake Lock API in JavaScript

Last updated: December 13, 2024

As web applications become more advanced, maintaining a proper user experience remains crucial, especially for applications requiring constant attention without interruption due to screen sleep. Thankfully, with modern browsers, we have access to the Screen Wake Lock API in JavaScript, which allows web applications to request a screen wake lock, thereby preventing the device's screen from dimming or locking.

Understanding the Screen Wake Lock API

The Screen Wake Lock API is a relatively new browser feature. Notably, it prevents devices from automatically turning off the screen, which can be vital during video conferences, reading long documents, or gaming sessions. Before its implementation, developers had to rely on hacks like continuously scrolling or preventing touch events, which were far from ideal.

How to Use the Screen Wake Lock API

Implementing the Screen Wake Lock API in your web applications involves a couple of simple steps. The first step is to request the wake lock, and then you need to release it when the application no longer requires it.

Below is a basic example to illustrate how you can use this API in your web applications:


// Ensure that the Wake Lock API is available
if ('wakeLock' in navigator) {
    let wakelock = null;
    
    // Create an async function to request a wake lock
    async function requestWakeLock() {
        try {
            // Request the screen wake lock
            wakelock = await navigator.wakeLock.request('screen');
            console.log('Wake Lock is active!');

            // Listen for the 'release' event
            wakelock.addEventListener('release', () => {
                console.log('Wake Lock was released');
            });
        } catch (err) {
            // Handle the error, e.g., display a message to the user
            console.error(`Could not obtain wake lock: ${err.name}, ${err.message}`);
        }
    }

    // Automatically release the wake lock when the page is hidden
    document.addEventListener('visibilitychange', () => {
        if (wakelock !== null && document.hidden) {
          wakelock.release()
            .then(() => console.log('Wake lock on page visibility change.'));
        } else if (!document.hidden) {
          requestWakeLock();
        }
    });

    // Request wake lock when needed
    requestWakeLock();
}

Handling Wake Lock Lifecycle

One of the most notable aspects of managing wake locks efficiently is handling their lifecycle properly. When a wake lock is released, the 'release' event triggers, allowing developers to update UI elements or trigger further actions.

Additionally, a critical feature to note is managing the wake lock across different visibility states of the page to prevent unnecessary battery drainage when the application isn't actively viewed.

Browser Support and Considerations

The API is available in most modern browsers, although there might be discrepancies in support and behavior. Developers should be certain to implement feature detection as demonstrated in the example above, ensuring the code degrades gracefully when the API is not available.

Moreover, there may be exceptions or errors during wake lock requests which should be handled explicitly in the application to inform or gently prompt users when the functionality cannot proceed as intended.

Conclusion

The Screen Wake Lock API enhances web applications by providing more control over device behavior when dealing with user interaction, particularly for applications needing screens to stay awake. By understanding and improving the handling of this feature, you enable more reliable and user-friendly web application experiences.

Next Article: Keep Critical Info Visible Using JavaScript Wake Locks

Previous Article: Adjust UI Based on Orientation Changes via 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