-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeedo.js
More file actions
80 lines (63 loc) · 2.07 KB
/
speedo.js
File metadata and controls
80 lines (63 loc) · 2.07 KB
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
import { getLocalState, saveState } from './state.js'
const input = document.getElementById('speed')
async function getCurrentTab() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
return tab.id;
}
function clearIntervalTab(pid) {
// console.log(`> removing interval ${pid}`)
clearInterval(pid);
return undefined;
}
function continuousSpeedPlayers(speed) {
[...document.querySelectorAll('video')].forEach(player => player.playbackRate = speed);
const pid = setInterval(function () {
// console.log(`> running interval to speedUp ${speed}x ${pid}`);
[...document.querySelectorAll('video')].forEach(player => player.playbackRate = speed);
}, 500);
// console.log(`> created interval to speedUp ${speed}x ${pid}`);
return pid;
}
function resetPlayers() {
// console.log(`> reset speed to 1x`);
[...document.querySelectorAll('video')].forEach(player => player.playbackRate = 1);
}
async function tabExecPromise(tabId, func, args) {
return new Promise((resolve, reject) => {
chrome.scripting.executeScript(
{
target: { tabId },
func,
args,
},
(executionReturn) => {
if(executionReturn && executionReturn[0]) {
resolve(executionReturn[0].result)
}
resolve()
}
);
})
}
async function updateSpeedRate(newSpeed) {
const tabId = await getCurrentTab()
const state = await getLocalState(tabId)
if(newSpeed === state.speed) return;
state.speed = newSpeed
if(state.pid) {
state.pid = await tabExecPromise(tabId, clearIntervalTab, [state.pid])
}
if(newSpeed === 1) {
state.pid = await tabExecPromise(tabId, resetPlayers, [])
} else {
state.pid = await tabExecPromise(tabId, continuousSpeedPlayers, [state.speed])
}
chrome.action.setBadgeText({text: `${newSpeed}x`});
await saveState(state)
}
(async function () {
const tabId = await getCurrentTab()
const { speed } = await getLocalState(tabId)
input.value = String(speed)
})()
input.addEventListener('change', (event) => updateSpeedRate(Number(event.target.value)))