-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontentScript.js
More file actions
87 lines (71 loc) · 2.4 KB
/
contentScript.js
File metadata and controls
87 lines (71 loc) · 2.4 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
(() => {
let youtubeLeftControls, youtubePlayer;
let currentVideo = '';
let currentVideoBookmarks = [];
const fetchBookmarks = () => {
return new Promise((resolve) => {
chrome.storage.sync.get([currentVideo], (obj) => {
resolve(obj[currentVideo] ? JSON.parse(obj[currentVideo]) : []);
});
});
};
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)
),
});
};
const newVideoLoaded = async () => {
const bookmarkBtnExists =
document.getElementsByClassName('bookmark-btn')[0];
currentVideoBookmarks = await fetchBookmarks();
if (!bookmarkBtnExists) {
const bookmarkBtn = document.createElement('img');
bookmarkBtn.src = chrome.runtime.getURL('assets/bookmark.png');
bookmarkBtn.className = 'ytp-button ' + 'bookmark-btn';
bookmarkBtn.title = 'Click to bookmark current timestamp';
youtubeLeftControls =
document.getElementsByClassName('ytp-left-controls')[0];
youtubePlayer = document.getElementsByClassName('video-stream')[0];
youtubeLeftControls.appendChild(bookmarkBtn);
bookmarkBtn.addEventListener('click', addNewBookmarkEventHandler);
}
};
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);
}
});
let trail = '&ytExt=ON';
if (
!window.location.href.includes(trail) &&
!window.location.href.includes('ab_channel') &&
window.location.href.includes('youtube.com/watch')
) {
window.location.href += trail;
}
})();
const getTime = (t) => {
var date = new Date(0);
date.setSeconds(t);
return date.toISOString().substr(11, 8);
};