Stop The Screen Going To Sleep With 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
Hands Covered in Dough by Anastasia Shuraeva via

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.

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.

To actually lock the wake state, we need to call request on our the wakeLock object in the navigator. We can also wrap a couple of console.log statements around it to ensure that we can see alerts when the state changes.

We've put the code in a try catch loop as navigator.wakeLock could potentially exist in some other state than we're expecting and that would cause errors.

At this point we have a window which can prevent the screen from sleeping. At some point we're likely going to want to release the lock and to do that, we call release on our wakelock variable.

With those two functions set up we can keep our screen awake for as long as we need. If we only need to lock the wake state for a short period, we can even use these with a setTimeout like so.

And just like that, you've finished implementing wakeLock.

I am a little concerned about the lack of security on this API given it's potential to keep the machine from sleeping, however due to the limitations of running only on active tabs I suppose its scope for abuse is limited.

I love how simple this API is. It doesn't have any features that you don't need and works with very little setup. Hopefully, you'll have noticed that while reading this blog post, your browser hasn't let your computer go to sleep. That being said, I have set it up to release the sleep lock state once you scroll into the comment section.

Also, while I have included console.logs on this blog post. They won't exist on any of the others.

Michael Walter Van Der Velden
Loading Comments