-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyoutube-tools.js
54 lines (49 loc) · 1.54 KB
/
youtube-tools.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
import qs from "https://jspm.dev/qs"
/**
* @param {string} selectors
* @return {HTMLElement[]}
*/
// @ts-ignore
const $$ = selectors => [...document.querySelectorAll(selectors)]
const waitFor = (isReady = () => true, delay = 10) => {
return new Promise(done => {
const loop = () => {
const result = isReady()
if (result != null) {
done(result)
} else {
setTimeout(loop, delay)
}
}
loop()
})
}
const timeout = (time = 100) => new Promise(done => setTimeout(done, time))
const nextFrame = () => new Promise(done => requestAnimationFrame(done))
/** @return {Promise<import("./YouTube").CueGroup[] | null>} */
export async function getTranscriptCueGroups(TIMEOUT = 5000) {
const startTime = Date.now()
while (getTranscript().length === 0) {
clickOpenMenu()
// await nextFrame()
await timeout(100)
clickOpenTranscript()
await timeout(100)
if (Date.now() - startTime > TIMEOUT) {
return null
}
}
return getTranscript()
}
/** @return {import("./YouTube").CueGroup[]} */
const getTranscript = () =>
// @ts-ignore
$$("ytd-transcript-renderer")[0]?.__data?.data?.body?.transcriptBodyRenderer
?.cueGroups ?? []
const clickOpenTranscript = () =>
[...$$("ytd-menu-service-item-renderer")]
.filter(it => it.textContent?.includes("Open transcript"))
.map(b => b.click()).length > 0
const clickOpenMenu = () =>
[...$$('[aria-label="More actions"]')].forEach(b => b.click())
export const getCurrentPageUid = () => qs.parse(location.search, { ignoreQueryPrefix: true }).v