79 lines
2.1 KiB
JavaScript
79 lines
2.1 KiB
JavaScript
(() => {
|
|
'use strict';
|
|
|
|
const button = document.querySelector('#wakeLockBtn');
|
|
if (!button) return;
|
|
|
|
let wakeLock = null;
|
|
let wanted = false;
|
|
|
|
function tr(key, fallback) {
|
|
return typeof window.controlT === 'function' ? window.controlT(key) : fallback;
|
|
}
|
|
|
|
function supported() {
|
|
return 'wakeLock' in navigator;
|
|
}
|
|
|
|
function active() {
|
|
return wakeLock !== null && wakeLock.released === false;
|
|
}
|
|
|
|
function render() {
|
|
const isActive = active();
|
|
button.disabled = !supported();
|
|
button.classList.toggle('wake-active', isActive);
|
|
button.textContent = 'WakeLock';
|
|
button.title = supported() ? tr('wakeLockTitle', 'Prevent screen sleep') : tr('wakeLockUnsupported', 'WakeLock is not supported by this browser.');
|
|
}
|
|
|
|
async function requestWakeLock() {
|
|
if (!supported()) {
|
|
render();
|
|
return;
|
|
}
|
|
|
|
wakeLock = await navigator.wakeLock.request('screen');
|
|
wakeLock.addEventListener('release', () => {
|
|
wakeLock = null;
|
|
render();
|
|
});
|
|
render();
|
|
}
|
|
|
|
async function releaseWakeLock() {
|
|
wanted = false;
|
|
if (wakeLock) {
|
|
await wakeLock.release();
|
|
}
|
|
wakeLock = null;
|
|
render();
|
|
}
|
|
|
|
button.addEventListener('click', () => {
|
|
const job = active() ? releaseWakeLock() : (async () => {
|
|
wanted = true;
|
|
await requestWakeLock();
|
|
})();
|
|
|
|
job.catch(error => {
|
|
wanted = false;
|
|
wakeLock = null;
|
|
const alertFn = window.customAlert || (() => Promise.resolve());
|
|
alertFn(error.message || 'WakeLock failed', {
|
|
title: tr('wakeLockErrorTitle', 'WakeLock Error'),
|
|
danger: true,
|
|
});
|
|
render();
|
|
});
|
|
});
|
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
if (document.visibilityState === 'visible' && wanted && !active()) {
|
|
requestWakeLock().catch(() => render());
|
|
}
|
|
});
|
|
|
|
render();
|
|
})();
|