2

I want to enable wake lock API. It is working fine with Windows platform and android devices but not in Safari or iOS devices.

Console has error NotAllowed, Permission was denied in Safari Browser.

I tried with below code

if ('wakeLock' in navigator && 'request' in navigator.wakeLock) {
     let wakeLock = null;

            const requestWakeLock = async () => {
                try {
                    wakeLock = await navigator.wakeLock.request('screen');
                    wakeLock.addEventListener('release', (e) => {
                        console.log(e);
                        console.log('Wake Lock was released');
                    });
                    console.log('Wake Lock is active');
                } catch (e) {
                    console.error(`${e.name}, ${e.message}`);
                }
            };

            requestWakeLock();

            const handleVisibilityChange = () => {
                if (wakeLock !== null && document.visibilityState === 'visible') {
                    requestWakeLock();
                }
            };

            document.addEventListener('visibilitychange', handleVisibilityChange);
}

Add button and trigger click also returns same error.

let button = document.createElement("button");
button.addEventListener('click', function(){
     console.log('button clicked');
     requestWakeLock();
});

button.click();

1 Answer 1

0

Update:

Sorry for the confusion, I did some tests and found wakeLock.request only works after we first touched the screen on iOS. I added

document.addEventListener('click', () => {     
    navigator.wakeLock.request() 
})

and it works.

It seems like iOS(17.5.1) has this issue, I found an issue(https://bugs.webkit.org/show_bug.cgi?id=254545) related to this problem.

4
  • let button = document.createElement("button"); button.addEventListener('click', function(){ console.log('button clicked'); requestWakeLock(); }); button.click(); I did this code but same error. I do not want to show button to the user. Commented Jul 4 at 11:17
  • do you use https?
    – Leo
    Commented Jul 4 at 15:40
  • my observation is, the request of wake lock won't be approved before you touch the document, so document.addEventListener('click', () => { navigator.wakeLock.request() }) might work
    – Leo
    Commented Jul 4 at 16:51
  • I am using https. Using click event it is working but I want to active it without any user interaction. Commented Jul 8 at 12:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.