0

So I am developing a chrome extension. I am trying to get the Youtube video current playing time

I am aware that there are many similar questions asked in other posts, but none of their code works for me

My code is like this, I have to inject my code to the content script first

chrome.tab.query({highlighted: true}, tabs => {
   tab = tabs[0]
   chrome.tabs.executeScript(tab.id, {code: "temp = 
                             document.getElementById('movie_player'); 
alert(temp); alert(temp.getCurrentTime());"}, respond => {});
}

So when I run this, I will get an alert saying [object HTMLDivElement]. but won't get anything from temp.getCurrentTime().

qwdh
  • 85
  • 1
  • 7

2 Answers2

2

Problems:

  • An element is a complex object so it can't be displayed by alert() in a meaningful way, which is why you see [object HTMLDivElement]. You don't need it, anyway, it was a test, I guess.

  • The actual problem is that #movie_player is a <div> with a lot of YouTube Player API functions exposed in the page context, but not in the isolated world where all content scripts run. To access the page context you would have to use a page script yourself, which is unnecessarily complicated.

Solution:

Access the <video> element which exposes currentTime as a standard DOM property so it's available both in the page context and in the isolated world of content scripts. Then transfer the result into the callback by making it the last expression in the code string:

chrome.tabs.executeScript({
  code: 'document.querySelector("video").currentTime'
}, results => {
  const time = results && results[0];
  console.log(time);
});
  • the result should be a simple type like a string/number/boolean/null or an array/object consisting of such simple types, meaning you can't transfer DOM elements and functions;
  • the result should be used inside the callback because it's invoked asynchronously, meaning it runs at a later time in the future, after the outer code has already finished, more info: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference;
  • if you always want to process the active tab you don't need to specify the tabId in executeScript() so you don't need chrome.tabs.query() either.

Returning multiple properties:

chrome.tabs.executeScript({
  code: `(${() => {
    const el = document.querySelector('video');
    return {
      time: el.currentTime,
      duration: el.duration,
    };
  }})()`
}, results => {
  const info = results && results[0];
  console.log(info);
});
Community
  • 1
  • 1
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
0

The following code prints the youtube playtime in the console

chrome.tabs.executeScript(tab.tabId, {
    code: "var temp = document.getElementById('movie_player').innerText; temp"
}, function(results) {
    console.log(results);
}); 
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Aqid
  • 76
  • 2