-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyt_eventer.js
67 lines (57 loc) · 1.91 KB
/
yt_eventer.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
var player = document.getElementsByTagName("video")[0]
var funcsToExecute = []
var functionsMarkers = []
// AddVideoAction:
// - timing: timestamp in seconds of the video when func will be executed
// - func: function to be executed (without parameters)
function AddVideoAction(timing, func) {
funcsToExecute.push({
timing: timing,
func: func
})
if (videoPlaying() && timing > player.currentTime) {
functionsMarkers.push(setTimeout(func, (timing - player.currentTime) * 1000))
}
}
function videoPlaying() {
if (player.currentTime <= 0) {
return false
}
if (player.paused === true || player.ended === true) {
return false
}
return true
}
function playerReadiness () {
var currentTimestamp = event.target.currentTime
console.log("Re-adding functions...")
console.log(`${funcsToExecute.length} functions to re-add`)
funcsToExecute.forEach(funcToExecute => {
if (funcToExecute.timing > currentTimestamp) {
var timeBeforeExecution = (funcToExecute.timing - currentTimestamp) * 1000
console.log("Executing function in ", timeBeforeExecution, "ms")
var functionMarker = setTimeout(funcToExecute.func, timeBeforeExecution)
functionsMarkers.push(functionMarker)
}
})
console.log("Functions re-attached!")
}
function cancelAllFunctions() {
functionsMarkers.forEach(marker => {
clearTimeout(marker)
})
functionsMarkers = []
console.log("Functions canceled!")
}
function attachEventListener(player) {
player.addEventListener('playing', playerReadiness)
player.addEventListener('playing', () => { console.log('video playing') })
player.addEventListener('pause', cancelAllFunctions)
player.addEventListener('pause', () => { console.log('video paused') })
player.addEventListener('ended', cancelAllFunctions)
player.addEventListener('ended', () => { console.log('video ended') })
}
if (!!player) {
attachEventListener(player)
player.volume = 0.25
}