Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reacquire wake lock as needed #1158

Merged
merged 2 commits into from
Jan 28, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
GarboMuffin marked this conversation as resolved.
Show resolved Hide resolved
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