An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
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
:
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:
Then, when pressed, the icon changes to an open, green eye:
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; }); } })}
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:
--
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">
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To