用JavaScript阻止屏幕入睡

We've all been there. Cooking a complex recipe where each step takes a good couple of minutes. Our hands covered in some type of sauce made of who knows how many ingredients. We go to check the next step on our phone only to see that it's gone to sleep due to inactivity. We know that even if we quickly wash our hands, there is inevitably going to be some level of greasy trail left on our phone screen as we are forced to unlock it...

我们都经历过这种情况。烹饪一个复杂的食谱,每个步骤都需要好几分钟。我们的双手沾满了某种不知由多少种成分制成的酱汁。我们去查看手机上的下一个步骤,却发现它由于不活动而进入了睡眠状态。我们知道,即使我们迅速洗手,也不可避免地会在我们的手机屏幕上留下某种程度的油渍痕迹,因为我们被迫解锁它......

Hands Covered in Dough by Anastasia Shuraeva via https://www.pexels.com/@anastasia-shuraeva/

Hands Covered in Dough by Anastasia Shuraeva via https://www.pexels.com/@anastasia-shuraeva/

Hands Covered in Dough by Anastasia Shuraeva viahttps://www.pexels.com/@anastasia-shuraeva/

However, thanks to a web API released in chrome 85, this doesn't need to be an issue any more. The Screen Wake Lock API allows us to stop the device screen from going to sleep without hacky work arounds that are likely to drain the battery of the device (Such as NoSleep.js). It is unfortunately unsupported in Firefox and Safari but I don't imagine that Firefox will be too far behind on this implementation.

然而,由于chrome 85中发布了一个网络API,这不再需要成为一个问题了。屏幕唤醒锁API允许我们阻止设备屏幕进入睡眠状态,而不需要采用可能会耗尽设备电池的黑客工作方法(如NoSleep.js)。不幸的是,它在Firefox和Safari中不被支持,但我不认为Firefox会在这个实现上落后太多。

Wake Lock only works on active tabs/windows, which I'm sure you'll all agree is a good idea. This prevents background tabs from keeping your device awake but it can also be released manually via code at any point (eg. when your blog post has finished being read).

唤醒锁只对活动标签/窗口起作用,我相信你们都会同意这是个好主意。这可以防止后台标签让你的设备保持清醒,但它也可以在任何时候通过代码手动释放(例如,当你的博客文章完成阅读时)。

To implement wake lock we first need to check if the feature exists in the current browser. We can do this with the following simple function.

为了实现唤醒锁,我们首先需要检查该功能在当前浏览器中是否存在。我们可以用下面这个简单的函数来实现。

const canWakeLock = () => 'wakeLock' in navigator;

To actually lock the wake state, we need to call request on our the wakeLock object in the navigator. We can also wrap a...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.124.0. UTC+08:00, 2024-04-24 11:20
浙ICP备14020137号-1 $访客地图$