Skip to content

Commit

Permalink
DNin/wake-lock: Reacquire wake lock as needed (#1158)
Browse files Browse the repository at this point in the history
Resolves #1120

Currently, if you request a wake lock with the Wake Lock extension and
then navigate away from the page, the wake lock gets released in the
background because wake locks are automatically released when the
document gets hidden, plus, the extension isn't aware of when this
happens, so you have no way of knowing.

This change makes the extension automatically request another wake lock
when the document regains visibility after having been hidden. It still
reports to the project that the wake lock is enabled when this happens,
therefore projects will act like nothing happened but the wake lock will
still be there as long as you come back. I also considered the
possibility of projects enabling or disabling wake lock when the
document is hidden and now handle it properly.

I tested these changes in Edge to the best of my ability.
  • Loading branch information
DNin01 authored Jan 28, 2024
1 parent 9e620cb commit db49c37
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion extensions/DNin/wake-lock.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@
constructor(runtime) {
this.runtime = runtime;
this.runtime.on("PROJECT_STOP_ALL", this.stopAll.bind(this));

document.addEventListener("visibilitychange", () => {
// If enabled, reacquire wake lock when document becomes visible again
if (wakeLock !== null && document.visibilityState === "visible") {
latestEnabled = false;
this.setWakeLock({
enabled: true,
});
}
});
}

getInfo() {
Expand Down Expand Up @@ -77,14 +87,26 @@
// Not supported in this browser.
return;
}
const enable = Scratch.Cast.toBoolean(args.enabled);
if (enable && document.visibilityState === "hidden") {
// Can't request wake lock while document is hidden.
return;
}

const previousEnabled = latestEnabled;
latestEnabled = Scratch.Cast.toBoolean(args.enabled);
latestEnabled = enable;
if (latestEnabled && !previousEnabled) {
promise = promise
.then(() => navigator.wakeLock.request("screen"))
.then((sentinel) => {
wakeLock = sentinel;
wakeLock.addEventListener("release", () => {
if (document.visibilityState === "visible") {
// If the document is hidden, wake lock should be reacquired when it's visible again.
wakeLock = null;
latestEnabled = false;
}
});
})
.catch((error) => {
console.error(error);
Expand Down

0 comments on commit db49c37

Please sign in to comment.