-
Notifications
You must be signed in to change notification settings - Fork 0
/
fbVolSync.js
64 lines (50 loc) · 1.62 KB
/
fbVolSync.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
const get = key => new Promise(resolve => {
chrome.storage.sync.get(key, items => {
resolve(items[key]);
});
});
const set = items => new Promise(resolve => {
chrome.storage.sync.set(items, resolve);
});
let desiredVolume = 0.5;
let allVideos = [...document.getElementsByTagName('video')];
const updateVideos = () => {
allVideos.forEach(video => {
video.volume = desiredVolume;
});
};
const persistVolume = () => {
set({ desiredVolume });};
const handleVolumeChange = event => {
desiredVolume = event.target.volume;
updateVideos();
persistVolume();
};
const observer = new MutationObserver(mutations => {
const addedVideos = mutations.reduce((accumulator, mutation) => {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
const videos = [...mutation.addedNodes]
.filter(({ tagName }) => tagName && tagName.toLowerCase() === 'div')
.map(node => node.getElementsByTagName('video'))
.filter(collection => collection.length)
.flatMap(video => [...video]);
if (videos.length > 0) {
accumulator.push(...videos);
}
}
return accumulator;
}, []);
if (addedVideos.length) {
allVideos = [...new Set([...allVideos, ...addedVideos])];
allVideos.forEach(video => {
video.volume = desiredVolume;
video.removeEventListener('volumechange', handleVolumeChange);
video.addEventListener('volumechange', handleVolumeChange);
});
}
});
(async function main() {
desiredVolume = await get('desiredVolume') || 0.5;
updateVideos();
observer.observe(document, { childList: true, subtree: true });
}());