Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
75 lines (71 loc) · 2.12 KB
/
Copy pathcontent.js
File metadata and controls
75 lines (71 loc) · 2.12 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
if (!self.browser && self.chrome) {
browser = chrome;
}
let cachedCanvas = null;
const toDataURL = (element) => {
try {
if (!cachedCanvas) {
cachedCanvas = document.createElement("canvas");
cachedCanvas.crossOrigin = "anonymous";
cachedCanvas.height = 720;
}
const canvas = cachedCanvas;
if (canvas.height !== 720) {
canvas.height = 720;
}
if (element instanceof HTMLVideoElement) {
canvas.width = (element.videoWidth / element.videoHeight) * canvas.height;
} else {
canvas.width = (element.width / element.height) * canvas.height;
}
canvas.getContext("2d").drawImage(element, 0, 0, canvas.width, canvas.height);
return canvas.toDataURL("image/jpeg", 0.9);
} catch (err) {
return null;
}
};
browser.runtime.sendMessage({ type: "getTargetSrc" });
browser.runtime.onMessage.addListener(({ action, srcUrl, currentTime }, sender, sendResponse) => {
if (action === "getSearchImage" && srcUrl) {
//assume only one element match the src
let element;
const imgs = document.getElementsByTagName("img");
for (let i = 0; i < imgs.length; i++) {
if (imgs[i].currentSrc === srcUrl) {
element = imgs[i];
break;
}
}
if (!element) {
const videos = document.getElementsByTagName("video");
for (let i = 0; i < videos.length; i++) {
if (videos[i].currentSrc === srcUrl) {
element = videos[i];
break;
}
}
}
if (!element) return alert("Fail to get search image");
if (currentTime && element instanceof HTMLVideoElement) {
element.pause();
element.volume = 0;
element.currentTime = currentTime;
element.oncanplay = () => {
const searchImage = toDataURL(element);
if (searchImage) {
sendResponse({ searchImage });
}
};
return true;
} else {
const searchImage = toDataURL(element);
if (searchImage) {
sendResponse({ searchImage });
} else {
sendResponse({
currentTime: element instanceof HTMLVideoElement ? element.currentTime : null,
});
}
}
}
});