skip to Main Content

I am using Javascript on Windows Chrome.

I can successfully set a wakelock and have tested that it does, in fact, prevent my screen from going dark. However, I’m not able to release it. The error I get is

wakeLock.release is not a function

I’ve also tried putting the release code in an async function and using await.

async function set_wakelock() {
    wakeLock = await navigator.wakeLock.request('screen');
    return wakeLock;
}

var wakeLock = set_wakelock();

// alert(wakeLock);  // Correctly shows [Object promise]

try {
    wakeLock.release();
    wakeLock = null;
}  catch (err) {
    alert(err); // wakeLock.release is not a function
}

2

Answers


  1. Chosen as BEST ANSWER

    From @derpirscher's comment, I needed to call release() a different way.

    async function set_wakelock() {
        wakeLock = await navigator.wakeLock.request('screen');
        // optional listener:
        wakeLock.addEventListener('release', () => {
             alert('Wake Lock was released');
        }); 
        return wakeLock;
    }
    
    function release_wakelock(){
        if  (! wakeLock){
            return;
        }
        try {
            wakeLock.then(wls => wls.release())
            wakeLock = null;
        }  catch (err) {
            // alert(err);
        }
    }
    
    var wakeLock = null;
    wakeLock =  set_wakelock();
    release_wakelock();
    
    // note: should first check that navigator.wakeLock is supported by the browser.
    

  2. The set_wakelock is an async method, therefore the immediate return is a promise. Change your code to await for the result

    var wakeLock = await set_wakelock();
    

    Something like:

    async function set_wakelock() {
      wakeLock = await navigator.wakeLock.request('screen');
      return wakeLock;
    }
    
    var wakeLock = await set_wakelock();
    
    // Use the wakelock here...
    
    // Release the wakelock after you have finished using it
    await wakeLock.release();
    wakeLock = null;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search