0

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.

A Ahad
  • 35
  • 5
  • Does this answer your question? [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Carcigenicate May 28 '21 at 17:26
  • `get_time` doesn't return anything. `log` is being called from inside of a function that's called asynchronously. That's a separate mechanism from `return`ing. – Carcigenicate May 28 '21 at 17:26
  • Based on what I could understand from the link, the `get_time` function is asynchronous because it is passing a message and waiting for the response? So if I use return promise there, with the resolve being the `response.timestamp`, then it should work? Sorry if this seems noobish. I'm fairly new to javascript and while the concept behind asynchronous functions is easy enough to understand, I'll need a lot more practice before I'm comfortable with the execution. – A Ahad May 29 '21 at 02:08

0 Answers0