forked from gurumukhi/youtube-screenshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
content_script.js
executable file
·332 lines (266 loc) · 9.31 KB
/
content_script.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
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Logger is disabled by default
function logNull(message) {
// Nothing
}
function logConsole(message) {
console.log(`Youtube Screenshot Addon: ${message}`);
}
let logger = logNull;
let currentConfiguration = {
downloadFile: true,
copyToClipboard: false,
// Image format
imageFormat: "image/jpeg",
imageFormatExtension: "jpeg",
shortcutEnabled: true,
};
// Shorts container tag and active attribute
const shortsContainerTag = "ytd-reel-video-renderer";
const shortsContainerTagName = shortsContainerTag.toUpperCase();
const shortsContainerActiveAttribute = "is-active";
// Take screenshot
captureScreenshot = function () {
logger("Capturing screenshot");
// Several <video> tags can be present in the document at the same time
// Sometimes (e.g. Youtube Shorts), the first is not the one playing the current stream
// Add "src" attribute filter however seems to do the trick
let video = document.querySelector("video[src]");
if (video.mediaKeys != null) {
browser.runtime.sendMessage({cmd: "showProtectionError"});
return;
}
let canvas = document.createElement("canvas");
let ctx = canvas.getContext("2d");
canvas.width = parseInt(video.videoWidth);
canvas.height = parseInt(video.videoHeight);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
if (currentConfiguration.copyToClipboard)
copyToClipboard(canvas);
if (currentConfiguration.downloadFile)
downloadFile(canvas, video);
};
function downloadFile(canvas, video) {
let a = document.createElement("a");
a.href = canvas.toDataURL(`${currentConfiguration.imageFormat}`);
a.download = getFileName(video);
a.style.display = "none";
document.body.appendChild(a);
a.click();
a.remove();
};
function copyToClipboard(canvas) {
logger("Copying to clipboard");
canvas.toBlob((blob) => {
// Send the data to background script as navigator.clipboard.write()
// is not yet supported by default on Firefox
browser.runtime.sendMessage({cmd: "copyToClipboard", data: blob})
.then((e) => {
if (e)
logger(`Failed to copy to clipboad: ${e.message}`);
else
logger("Successfully copied to clipboard");
});
}, "image/png");
}
function getFileName(video) {
let timeString = "";
const seconds = video.currentTime;
let mins = Math.floor(seconds / 60);
const secs = Math.floor(seconds - (mins * 60));
let s = secs.toString();
if (s.length == 1)
s = "0" + s;
if (mins >= 60) {
const hours = Math.floor(mins / 60);
mins -= (hours * 60);
let m = mins.toString();
if (m.length == 1)
m = "0" + m;
timeString = `${hours}-${m}-${s}`;
} else {
timeString += `0-`+`${mins}-${s}`;
}
return `${window.document.title} - ${timeString}.${currentConfiguration.imageFormatExtension}`;
};
function addButtonOnPlayer(container, regularNotShorts) {
const btnClass = regularNotShorts ? "ytp-screenshot" : "ytd-screenshot";
const type = regularNotShorts ? "regular" : "shorts";
// Check if button already present
let previousBtn = container.querySelector(`button.${btnClass}`);
if (previousBtn) {
logger(`Removing previous ${type} screenshot button`);
previousBtn.remove();
}
logger(`Adding ${type} screenshot button`);
let btn = document.createElement("button");
let t = document.createTextNode("Screenshot");
if (regularNotShorts) {
btn.classList.add("ytp-time-display");
btn.classList.add("ytp-button");
} else {
btn.classList.add("ytd-shorts-player-controls");
btn.style.color = getComputedStyle(container.querySelector("yt-icon")).color;
btn.style.border = "none";
btn.style.cursor = "pointer";
btn.style.background = "none";
// Ensure the pointer event are not disabled for our custom button
btn.style.pointerEvents = "all";
}
btn.classList.add(btnClass);
btn.style.width = "auto";
btn.appendChild(t);
if (regularNotShorts)
container.insertBefore(btn, container.firstChild);
else
container.insertBefore(btn, container.querySelector("yt-icon-button").nextSibling);
logger(`Adding ${type} button event listener`);
btn.removeEventListener("click", captureScreenshot);
btn.addEventListener("click", captureScreenshot);
};
function observeShortsContainer(element, shortsCallback) {
logger("Observe shorts container");
let observer = new MutationObserver((mutations) => {
for (const mutation of mutations)
{
if (mutation.attributeName != shortsContainerActiveAttribute)
continue;
if (element.getAttribute(shortsContainerActiveAttribute) == null) {
// No more the active container
observer.disconnect();
// Find the new active container
const container = document.querySelector(`${shortsContainerTag}[${shortsContainerActiveAttribute}]`);
if (!container) {
logger("No more active shorts container");
continue;
}
retrieveShortsControls(container, shortsCallback);
break;
}
}
});
observer.observe(element, { attributes: true, childList: false, subtree: false });
}
function retrieveShortsControls(container, shortsCallback) {
const controls = container.querySelector("ytd-shorts-player-controls");
if (controls) {
// Monitor container to catch when active one changes
observeShortsContainer(container, shortsCallback);
logger("Found shorts controls");
shortsCallback(controls);
}
}
function waitForControls(regularCallback, shortsCallback) {
logger("Wait for controls");
const regularControlsClass = "ytp-right-controls";
const regularControls = document.querySelector(`.${regularControlsClass}`);
if (regularControls)
regularCallback(regularControls);
const shortsContainer = document.querySelector(`${shortsContainerTag}[${shortsContainerActiveAttribute}]`);
if (shortsContainer)
retrieveShortsControls(shortsContainer, shortsCallback);
// Monitor controls:
// - wait for them to be added to document
// - detect when switching from regular to shorts or vice versa
logger("Monitor controls");
let observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (!mutation.addedNodes)
return;
for (let element of mutation.addedNodes) {
if (element.nodeType != Node.ELEMENT_NODE)
continue;
if (element.classList.contains(regularControlsClass)) {
logger("Found regular controls");
regularCallback(element);
continue;
}
if ((element.tagName === shortsContainerTagName)
&& (element.getAttribute(shortsContainerActiveAttribute) != null)) {
retrieveShortsControls(element, shortsCallback);
break;
}
}
}
});
observer.observe(document.body, { childList: true, subtree: true });
}
async function loadConfiguration() {
logger("Load configuration");
const result = await browser.storage.local.get();
if (result.YouTubeScreenshotAddonisDebugModeOn) {
logger = logConsole;
logger("Logger enabled");
} else {
logger = logNull;
}
// Shortcut
currentConfiguration.shortcutEnabled = result.shortcutEnabled ?? true;
logger(`${currentConfiguration.shortcutEnabled ? "Enabling" : "Disabling"} screenshot shortcut`);
// Button action and image format
if (result.screenshotAction === "clipboard") {
currentConfiguration.downloadFile = false;
currentConfiguration.copyToClipboard = true;
} else if (result.screenshotAction === "both") {
currentConfiguration.downloadFile = true;
currentConfiguration.copyToClipboard = true;
} else {
// screenshotAction === "file"
currentConfiguration.downloadFile = true;
currentConfiguration.copyToClipboard = false;
}
if (currentConfiguration.downloadFile) {
if (result.imageFormat === "png") {
currentConfiguration.imageFormat = "image/png";
currentConfiguration.imageFormatExtension = "png";
} else {
currentConfiguration.imageFormat = "image/jpeg";
currentConfiguration.imageFormatExtension = "jpeg";
}
logger(`Setting image format to: ${currentConfiguration.imageFormat}`);
}
}
// Initialization (logger is not yet really initialized for the moment)
console.log("Initializing Youtube Screenshot Addon");
loadConfiguration().then(() => {
waitForControls(
(regularControls) => {
addButtonOnPlayer(regularControls, true);
},
(shortsControls) => {
addButtonOnPlayer(shortsControls, false);
}
);
});
// Handle messages
browser.runtime.onMessage.addListener(request => {
logger("Received message from background script");
if (request.cmd === "reloadConfiguration")
loadConfiguration();
return Promise.resolve({});
});
// Handle shortcut
document.addEventListener('keydown', e => {
if (!currentConfiguration.shortcutEnabled) {
logger("Shortcut is disabled");
return;
}
const tagName = e.target.tagName;
if (e.target.isContentEditable
|| (tagName === "INPUT")
|| (tagName === "SELECT")
|| (tagName === "TEXTAREA")) {
return;
}
if (!e.shiftKey)
return;
if ((e.key === 'a') || (e.key === 'A')) {
logger("Catching screenshot shortcut");
// Simply search for the screenshot button and simulate click
let btn = document.querySelector("button.ytp-screenshot")
|| document.querySelector("button.ytd-screenshot");
if (btn) {
btn.click();
return;
}
}
});