Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 17, 2021 04:01 pm GMT

Staying Alive: The Screen Wake Lock API

Friday night I was cooking a delicious vegetarian bolognese but was annoyed that my iPhone kept dimming the screen, and soon after locking the screen. I know that I can change the "time-to-lock" (or whatever it's called!?) in Settings, but wouldn't it be smarter, if we could tell a webpage to "stay alive"?

The Screen Wake Lock API does exactly that but, at the moment, only in Chrome.

To test it, I used Chrome on my MacBook.

First, I set the Turn display off after to 1 min:

Battery Settings BigSur

Then I added a checkbox for turning on/off the Wake Lock API. The checkbox is hidden and it's label shown as an icon the crossed-out, grey eye at the top right corner:

screenWakeLockDisabled

Then, when pressed, the icon changes to an open, green eye:

screenWakeLockEnabled

The JavaScript-code for toggling the Screen Wake Lock is pretty straight-forward:

const wakeLockToggle = document.querySelector('[data-wake-lock] > input');if (wakeLockToggle && ('wakeLock' in navigator)) {  let wakeLock = null;  const wakeLockEnable = async () => {     try {      wakeLock = await navigator.wakeLock.request('screen');    } catch (err) {      console.error(`${err.name}, ${err.message}`);    }  }  wakeLockToggle.addEventListener('click', () => {    if (wakeLockToggle.checked) {      wakeLockEnable();    }    else {      wakeLock.release()      .then(() => {        wakeLock = null;      });    }  })}
Enter fullscreen mode Exit fullscreen mode

Next, I left the MacBook open, touching nothing.

As predicted, it dimmed the screen after one minute. Then I turned on the Screen Wake Lock and after 3 minutes the screen hadn't dimmed. Hooray!

Demo

Unfortunately, Codepen prevents the Screen Wake Lock API from loading due to a feature policy, but I've uploaded a demo here!

Bonus: Structured Markup

Using Google's Rich Snippets is a SEO bonus, so I've added it to the demo-recipe. Using Google's Rich Result Testing Tool, you can preview what Google sees:

Rich Snippet

--

Right-to-left

I used CSS Logical Properties for some of the styles, including border-block-start-width, padding-inline-start and margin-block-end.

If you inspect the demo-markup, change ltr to rtl at the top of the document:

<html lang="en-US" dir="ltr">
Enter fullscreen mode Exit fullscreen mode

I can only encourage sites with recipes to embrace the Screen Wake Lock API!

Thanks for reading!


Original Link: https://dev.to/madsstoumann/staying-alive-the-screen-wake-lock-api-31fh

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To