Staying Alive: The Screen Wake Lock API
source link: https://dev.to/madsstoumann/staying-alive-the-screen-wake-lock-api-31fh
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Staying Alive: The Screen Wake Lock API
Jan 18
・2 min read
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!
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!
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK