Skip to content

Commit

Permalink
fix: Avoid wake lock request when document is hidden
Browse files Browse the repository at this point in the history
Check document visibility before requesting a wake lock to prevent Firefox's
DOMException ("The requesting document is hidden") error. The wake lock is
only requested if the document is visible and released when it becomes hidden.
  • Loading branch information
do0ori committed Feb 18, 2025
1 parent 06c75ad commit 7291694
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/hooks/useWakeLock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ export const useWakeLock = (enabled = true) => {
const wakeLockRef = useRef<WakeLockSentinel | null>(null);

const requestWakeLock = async () => {
if (document.visibilityState !== 'visible') {
console.debug('Document is not visible; skipping wake lock request.');
return;
}

if (!wakeLockRef.current) {
try {
if ('wakeLock' in navigator) {
Expand Down Expand Up @@ -35,7 +40,7 @@ export const useWakeLock = (enabled = true) => {
const manageWakeLock = async () => {
console.debug('manageWakeLock');
if (enabled) {
if (wakeLockRef.current === null) {
if (document.visibilityState === 'visible' && wakeLockRef.current === null) {
await requestWakeLock();
}
} else {
Expand All @@ -46,11 +51,19 @@ export const useWakeLock = (enabled = true) => {
const handleVisibilityChange = async () => {
console.debug('handleVisibilityChange');
if (document.visibilityState === 'visible' && enabled) {
await manageWakeLock(); // Restore Wake Lock if needed
await manageWakeLock();
} else if (document.visibilityState !== 'visible') {
await releaseWakeLock();
}
};

manageWakeLock(); // Initial setup
// Initial setup
if (document.visibilityState === 'visible') {
manageWakeLock();
} else {
console.debug('Document is hidden on mount. Not requesting wake lock.');
}

document.addEventListener('visibilitychange', handleVisibilityChange);

return () => {
Expand Down

0 comments on commit 7291694

Please # to comment.