I'm trying to get the timestamp of a YouTube video when a button is clicked on my extension. Right now, my code is setup like so:
contentScript.js
var time;
function get_timestamp() {
time = document.getElementsByClassName('video-stream')[0].currentTime
console.log(time);
return time;
};
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === "pause_video") {
pause_video();
}
if (request.message === "get_time") {
sendResponse({timestamp: get_timestamp()})
}
}
);
The pause function is also defined in the same file and works as expected.
popup.js
function get_time() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: "get_time"}, function(response) {
console.log(response.timestamp.toString());
return response.timestamp.toString();
});
})
};
popup2.js
document.getElementById("time").innerHTML = get_time();
The line in popup2.js is in a function that is called when the button is pressed. The script is split into 2 files as part of the testing, but they could be combined if necessary. The rest of the program works as expected, with functions to pause the video and get the videoID from the url working fine. All of the console.log commands show the current timestamp of the video, but I always get undefined when I use innerHTML. I feel like this ought to be simple but I can't figure out where the problem seems to be.