Disable Screen Sleep in JavaScript with WakeLock API
If you are not a Medium member, Click here to read the full article.
Preventing screen sleep using JavaScript is possible with the help of the WakeLock API. This feature is useful in certain scenarios, such as during long gaming sessions or while running test scripts. Here, we will provide you with a solution to prevent screen sleep using JavaScript.
Why Prevent Screen Sleep?
Under what circumstances would you need to prevent screen sleep? We introduce two examples:
1. During Gaming Sessions
While playing H5 games that run tasks in the background, screen sleep can cause the game’s progress to halt. Preventing screen sleep avoids such inconveniences.
2. Test Script Execution
Recently, we used Tampermonkey to create an automated testing script. This script, like the previous example, faced the same issue when the test case execution time was long. The display turned off during the testing process. To tackle this problem, we found a way to disable screen sleep during the script execution.
How to Prevent Screen Sleep?
Firstly, let’s check if the browser supports the WakeLock
API.