-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwakelock-toggle.js
69 lines (56 loc) · 1.49 KB
/
wakelock-toggle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class WakelockToggle extends HTMLElement {
constructor(element) {
super()
this.sentinel = null
this.label = 'Keep the screen on'
}
connectedCallback() {
const switcherId = 'wakelock'
const labelElement = document.createElement('label')
labelElement.setAttribute('for', switcherId)
labelElement.textContent = this.getAttribute('label') || this.label
const switcher = document.createElement('input')
switcher.id = switcherId
switcher.type = 'checkbox'
switcher.setAttribute('switch', '')
switcher.addEventListener('change', this)
const styleElement = document.createElement('style')
styleElement.textContent = `
wakelock-toggle {
display: flex;
justify-content: flex-start;
gap: 10px;
}
`
this.appendChild(styleElement)
this.appendChild(labelElement)
this.appendChild(switcher)
}
get switcherElement() {
return this.querySelector('input')
}
handleEvent(event) {
const value = this.switcherElement.checked
if (value) {
this.requestWakeLock()
} else {
if (this.sentinel !== null) {
this.sentinel.release().then(() => {
this.sentinel = null
})
}
}
}
async requestWakeLock() {
try {
this.sentinel = await navigator.wakeLock.request("screen")
this.sentinel.addEventListener("release", () => {
this.switcherElement.checked = false
})
} catch (err) {
console.info(`Couldn't activate WakeLock...`)
this.switcherElement.checked = false
}
}
}
customElements.define('wakelock-toggle', WakelockToggle)