I am trying to create a Chrome extension that bookmarks the parts of the YouTube video and stores the timestamp of the YouTube video in the localStorage. Below is the code I tried the following code, and I can see the array with all the timestamps but as soon as I refresh the page, the data is getting erased.
This is for checking if there are any timestamps for that video
// add listener to the message from the background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const { message, url } = request;
if (message === "newVideo") {
currentVideoURL = url.split("https://www.youtube.com/watch?v=")[1];
}
// checking the local storage for the bookmarks
chrome.storage.local.get([currentVideoURL]).then((result) => {
if (result[currentVideoURL]) {
bookmarksArray = JSON.parse(result[currentVideoURL]);
} else {
bookmarksArray = [];
}
});
console.log(bookmarksArray);
// this function only creates the icon element to display on the youtube player
createBookmarkBtn();
});
Below is the convertTime function that converts the time according to the time shown on youtube player and also stores the timestamp of the video in the localStorage
function convertTime(seconds) {
let hours = Math.floor(seconds / 3600);
let minutes = Math.floor((seconds % 3600) / 60);
let remainingSeconds = Math.floor(seconds % 60);
let formattedHours = hours.toString().padStart(2, "0");
let formattedMinutes = minutes.toString().padStart(2, "0");
let formattedSeconds = remainingSeconds.toString().padStart(2, "0");
let formattedTime = `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
const newBookmark = {
time: formattedTime,
desc: "Bookmark at " + formattedTime,
};
if (bookmarksArray.length === 0) {
bookmarksArray = [newBookmark];
} else {
bookmarksArray.unshift(newBookmark);
chrome.storage.local
.set({ currentVideoURL: JSON.stringify(bookmarksArray) })
.then(() => {
console.log("Data saved");
});
}
return formattedTime;
}