-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrol.js
More file actions
120 lines (97 loc) · 2.46 KB
/
control.js
File metadata and controls
120 lines (97 loc) · 2.46 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
const forwardedKeys = [
"Space",
"ArrowLeft",
"ArrowRight",
"ArrowUp",
"ArrowDown",
"Home",
"End",
];
const forwardedEvents = ["keydown", "keyup"];
const ignoredElements = ["INPUT", "TEXTAREA"];
class VideoEventBinder {
constructor() {
// this.videoContainer = null;
// this.targetElement = null;
// this.keyboardListener = null;
// this.binded = false;
this.createListeners();
this.bind();
}
createListeners() {
/**
* @param {KeyboardEvent} e
*/
this.keyboardListener = (e) => {
if (!e.isTrusted) {
// our generated event
return;
}
if (e.target && ignoredElements.includes(e.target.nodeName)) {
// https://github.com/ArthurCose/YouTube-Control-Fix/issues/3
return;
}
if (e.altKey || e.metaKey) {
// ignore if alt is active, common shortcut for the browser history
// ignore if the meta key is active, used by the OS
return;
}
if (!forwardedKeys.includes(e.code)) {
// we don't recognize this key
return;
}
const generatedEvent = new KeyboardEvent(e.type, e);
this.forwardElement.dispatchEvent(generatedEvent);
e.preventDefault();
e.stopImmediatePropagation();
};
}
bind() {
if (this.bindElements()) {
this.bindEvents();
return true;
}
return false;
}
bindElements() {
this.playerElement = document.querySelector("#content #player-container");
this.forwardElement = this.playerElement?.querySelector("#movie_player");
this.binded = this.playerElement && this.forwardElement;
return this.binded;
}
bindEvents() {
for (const eventName of forwardedEvents) {
this.playerElement.addEventListener(
eventName,
this.keyboardListener,
true
);
}
}
unbind() {
if (!this.binded) {
return;
}
this.binded = false;
this.playerElement = null;
this.forwardElement = null;
}
}
const videoBinder = new VideoEventBinder();
const observer = new MutationObserver((mutationList) => {
for (const mutation of mutationList) {
for (const node of mutation.removedNodes) {
if (
node == videoBinder.playerElement ||
node.contains(videoBinder.playerElement)
) {
videoBinder.unbind();
break;
}
}
}
if (!videoBinder.binded) {
videoBinder.bind();
}
});
observer.observe(document.body, { subtree: true, childList: true });