Created
March 27, 2026 15:52
-
-
Save cosimo/834a4989f6a4cb3a23855d7e9a07b671 to your computer and use it in GitHub Desktop.
How to get a screen awake lock on mobile
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <head> | |
| <title>Awake Test</title> | |
| <meta charset="utf-8"> | |
| <style type="text/css"> | |
| #wake-lock-toggle { | |
| padding: 8px 16px; | |
| border: 2px solid #ccc; | |
| border-radius: 8px; | |
| cursor: pointer; | |
| font-size: 1rem; | |
| } | |
| #wake-lock-toggle[data-active="true"] { | |
| border-color: #4caf50; | |
| background: #e8f5e9; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Awake Test</h1> | |
| <button id="wake-lock-toggle">π Keep Screen Awake</button> | |
| <script language=javascript> | |
| const btn = document.getElementById('wake-lock-toggle'); | |
| let wakeLock = null; | |
| async function requestWakeLock() { | |
| try { | |
| wakeLock = await navigator.wakeLock.request('screen'); | |
| wakeLock.addEventListener('release', () => { | |
| // Only update UI if not intentionally released | |
| if (!btn.dataset.active) return; | |
| }); | |
| btn.textContent = 'π Screen Awake'; | |
| btn.dataset.active = 'true'; | |
| } catch (err) { | |
| console.error(err); | |
| btn.dataset.active = ''; | |
| btn.textContent = 'π Keep Screen Awake'; | |
| } | |
| } | |
| async function releaseWakeLock() { | |
| if (wakeLock) { | |
| await wakeLock.release(); | |
| wakeLock = null; | |
| } | |
| btn.dataset.active = ''; | |
| btn.textContent = 'π Keep Screen Awake'; | |
| } | |
| btn.addEventListener('click', () => { | |
| if (btn.dataset.active) { | |
| releaseWakeLock(); | |
| } else { | |
| requestWakeLock(); | |
| } | |
| }); | |
| // Re-acquire on tab focus if toggle is on | |
| document.addEventListener('visibilitychange', () => { | |
| if (document.visibilityState === 'visible' && btn.dataset.active) { | |
| requestWakeLock(); | |
| } | |
| }); | |
| </script> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment