From efc5edfd1be0a1a9301f6bf6d5ec1fa37cc2c7c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Petr=20H=C3=A1la?= Date: Sun, 28 Jan 2024 16:35:56 +0100 Subject: [PATCH] Enhance wakeLock consistency --- backend/templates/songs/index.html | 39 +++++++++++++++++++++--------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/backend/templates/songs/index.html b/backend/templates/songs/index.html index f2f6035..fa50c34 100644 --- a/backend/templates/songs/index.html +++ b/backend/templates/songs/index.html @@ -184,22 +184,37 @@
<%:author%>
$.fn.DataTable.ext.pager.numbers_length = 5; $.templates("song", "#songTemplate") - let wakelock; + let wakeLock = null; + const requestWakeLock = async () => { + wakeLock = await navigator.wakeLock + .request('screen') + .catch(err => console.error('Failed to lock wake state with reason:', err.message)) + + console.log("Screen WakeLock turned on") + + // listen for our release event + wakeLock.onrelease = function(ev) { + console.log("Screen WakeLock released") + } + } + const handleVisibilityChange = () => { + if (wakeLock !== null && document.visibilityState === 'visible') { + requestWakeLock(); + } + } + async function preventSleep(value) { if(!canWakeLock()) return; if (value) { - try { - wakelock = await navigator.wakeLock.request(); - wakelock.addEventListener('release', () => { - console.log('Screen Wake State Locked:', !wakelock.released); - }); - console.log('Screen Wake State Locked:', !wakelock.released); - } catch(e) { - console.error('Failed to lock wake state with reason:', e.message); - } + await requestWakeLock() + document.addEventListener('visibilitychange', handleVisibilityChange); } else { - if(wakelock) wakelock.release(); - wakelock = null; + if(wakeLock) { + wakeLock.release().then(() => { + wakeLock = null; + document.removeEventListener('visibilitychange', handleVisibilityChange); + }); + } } } let hidden = false