Skip to content

Instantly share code, notes, and snippets.

@cosimo
Created March 27, 2026 15:52
Show Gist options
  • Select an option

  • Save cosimo/834a4989f6a4cb3a23855d7e9a07b671 to your computer and use it in GitHub Desktop.

Select an option

Save cosimo/834a4989f6a4cb3a23855d7e9a07b671 to your computer and use it in GitHub Desktop.
How to get a screen awake lock on mobile
<!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