-
Notifications
You must be signed in to change notification settings - Fork 1
/
tabVolume.js
82 lines (68 loc) · 2.48 KB
/
tabVolume.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* tabVolume
*
* Creates and manages the volume slider
*/
const VOLUMESTORE = 'bandcampVolume-volume';
var volume = localStorage.getItem(VOLUMESTORE);
volume = volume ? volume : 0.7;
var audioTag = document.getElementsByTagName("audio")[0];
var VolumeSliderPercent, volumeControl; // To store references to our control objects
var extensionRow = makeElement("tr", {id: "BandcampVolumeSlider"});
var rowTemplate = `
<template>
<td class="VolumeSliderCell" rowspan="2">
<label for="VolumeSliderPercent">Volume</label>
<span>
<input id="VolumeSliderPercent" type="number" min="0" max="100" step="1"/>
%
</span>
</td>
<td colspan="3">
<input id="VolumeSlider" type="range" min="0" max="1" step="0.01"/>
</td>
</template>
`;
function makeSlider() {
console.log("BandcampVolume: Adding Slider...");
// Add template to created element
// Rather than using 'innerHTML', set content safely
extensionRow.appendChild(
new DOMParser()
.parseFromString(rowTemplate, 'text/html')
.head.firstElementChild.content
)
if (document.getElementById("BandcampVolumeSlider")) {
// Replaces existing item rather than endlessly appending rows on extension reload
// Debug only
document.getElementById("BandcampVolumeSlider").parentNode.replaceChild(extensionRow, document.getElementById("BandcampVolumeSlider"));
} else {
// Add element to page
document.getElementById("trackInfoInner").children[0].children[0].children[0].appendChild(extensionRow);
}
VolumeSliderPercent = document.getElementById("VolumeSliderPercent");
volumeControl = document.getElementById("VolumeSlider");
setVolume(volume); // Set volume on load, also save the set volume
VolumeSliderPercent.addEventListener("change", function(){setVolume(VolumeSliderPercent.value/100)});
volumeControl.addEventListener("input", function(){setVolume(volumeControl.value)});
volumeControl.addEventListener("change", function(){setVolume(volumeControl.value)});
}
function makeElement(tag, options) {
return Object.assign(document.createElement(tag), options);
}
function setVolume(num) {
if (typeof num === 'undefined') return;
audioTag.volume = num;
saveVolume(num);
VolumeSliderPercent.value = percent_string(volume);
volumeControl.value = volume;
}
function percent_string(num) {
return `${(num * 100).toFixed(0)}`;
}
function saveVolume(num) {
if(num === null) return;
volume = num;
localStorage.setItem(VOLUMESTORE, num);
}
makeSlider();