JavaScript Wake Lock API

By  on  

An enjoyable web apps rely on engineers implementing the APIs that cover all of the small things. Those small things sometimes improve performance, usability, accessibility, and the app's relationship with its host system. The Wake Lock API is the latter -- an API that allows developers to instruct the host machine to not dim the screen or sleep, especially useful when users view videos.

To prevent the screen from dimming or sleeping, request permission to the screen:

let lock

try {
  lock = await navigator.wakeLock.request('screen');
} catch (err) {
  // Error or rejection
  console.log('Wake Lock error: ', err);
}

If the request is successful, the host machine doesn't sleep until released:

await lock.release()

I first saw this API implemented and utilized on mobile devices, and I'm happy to start seeing it utilized on desktop. There are a few big name streaming services that I've noticed could desperately use the Wake Lock API -- system sleep during videos ruins the experience!

Recent Features

  • By
    5 Ways that CSS and JavaScript Interact That You May Not Know About

    CSS and JavaScript:  the lines seemingly get blurred by each browser release.  They have always done a very different job but in the end they are both front-end technologies so they need do need to work closely.  We have our .js files and our .css, but...

  • By
    Introducing MooTools Templated

    One major problem with creating UI components with the MooTools JavaScript framework is that there isn't a great way of allowing customization of template and ease of node creation. As of today, there are two ways of creating: new Element Madness The first way to create UI-driven...

Incredible Demos

  • By
    Web Notifications API

    Every UI framework has the same set of widgets which have become almost essential to modern sites: modals, tooltips, button varieties, and notifications.  One problem I find is each site having their own widget colors, styles, and more -- users don't get a consistent experience.  Apparently the...

  • By
    SmoothScroll Using MooTools 1.2

    A while back I wrote a post about MooTools' SmoothScroll plugin which allows you to smoothly take a user to a specific portion of a page. By default, the browser "jerks" you up or down in the page when you click on an...

Discussion

  1. Really nice to see that this is becoming somewhat supported. I remember trying to use NoSleep.js (https://github.com/richtr/NoSleep.js) to hack this functionality in to a personal project.

  2. Great article thanks !
    I use the Wake Lock API too for a personal recipe app this is really usefull when cooking ‍
    I’ve open sourced a react module https://github.com/jorisre/react-screen-wake-lock

  3. joe
    Uncaught SyntaxError: await is only valid in async functions and async generators

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!