-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontentScript.js
81 lines (64 loc) · 2.58 KB
/
contentScript.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
(() => {
let youtubeLeftControls, youtubePlayer;
let currentVideo = "";
let currentVideoBookmarks = [];
chrome.runtime.onMessage.addListener((obj, sender, response) => {
const {type, value, videoId} = obj;
if(type === "NEW"){
currentVideo = videoId;
newVideoLoaded();
}
else if(type === "PLAY"){
youtubePlayer.currentTime = value;
}
else if(type === "DELETE"){
currentVideoBookmarks = currentVideoBookmarks.filter( (b) => b.time != value );
chrome.storage.sync.set({[currentVideo]: JSON.stringify(currentVideoBookmarks)})
response(currentVideoBookmarks);
}
});
// Fetch saved bookmarks function
const fetchBookmarks = () => {
return new Promise((resolve) => {
chrome.storage.sync.get([currentVideo], (obj) => {
resolve(obj[currentVideo] ? JSON.parse(obj[currentVideo]) : []);
})
})
}
// newVideoLoaded function
const newVideoLoaded = async () => {
const bookmarkBtnExists = document.getElementsByClassName("bookmark-btn")[0];
currentVideoBookmarks = await fetchBookmarks();
if(!bookmarkBtnExists){
// Create Bookmark Button
const bookmarkBtn = document.createElement("img");
bookmarkBtn.src = chrome.runtime.getURL("assets/bookmark.png");
bookmarkBtn.className = "ytp-button " + "bookmark-btn";
bookmarkBtn.title = "Bookmark current timestamp";
// Get YT controls
youtubeLeftControls = document.getElementsByClassName("ytp-left-controls")[0];
youtubePlayer = document.getElementsByClassName("video-stream")[0];
// Add Bookmark Button to left YT controls
youtubeLeftControls.appendChild(bookmarkBtn);
bookmarkBtn.addEventListener("click", addNewBookmarkEventHandler);
}
}
// Bookmark Event Handler Function
const addNewBookmarkEventHandler = async () => {
const currentTime = youtubePlayer.currentTime;
const newBookmark = {
time: currentTime,
desc: "Bookmark at " + getTime(currentTime),
}
currentVideoBookmarks = await fetchBookmarks();
chrome.storage.sync.set({
[currentVideo]: JSON.stringify([...currentVideoBookmarks, newBookmark].sort((a, b) => a.time - b.time))
})
}
newVideoLoaded();
})();
const getTime = t => {
var date = new Date(0);
date.setSeconds(t);
return date.toISOString().substring(11, 19);
}