Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current time of Youtube Video on youtube.com (e.g. document.getElementById('movie_player').getCurrentTime())

I'm creating a Google Chrome extension that relies on knowing the current time of a video being played on 'youtube.com'. I know, in principle, that document.getElementById('movie_player').getCurrentTime() should return this, but invoking this in a content script injected into the page produces:

Uncaught TypeError: document.getElementById('movie_player').getCurrentTime is not a function(…)

I am able to run the command in the Chrome console and get a proper return value.

And before this is flagged up as a duplicate question, I want to point out that I'm talking about doing this on 'youtube.com'. I dont know if I should expect special behavior, but this is definitely a different context than other questions I've found on stackoverflow.

To help, below is the simplest code I could come up with to reproduce this problem. To get it working, you'll need to load this as an unpacked extension. Then navigate to any youtube video. Click on the extension icon and click the "Start The Test" button. Also make sure you have the console open (F12).

Thanks in advance for suggestions for how to make this method work, or another way I can get the info I need (e.g. I looked into getting the share at time value but couldnt figure that one out). As a last resort, I'm considering replacing the youtube player with my own iframe and trying that way.

popup.html

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <script src='popup.js'></script>

  </head>
  <body>
    <input type='button' id='start' value='Start The Test'></input>
    <p id="messages"></p>
    <p id="result"></p>
  </body>

</html>

popup.js

// Add listener for start button
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("start").addEventListener('click', process_video);
});


function process_video() {
    chrome.tabs.executeScript(null, {file: 'test.js'});
}

test.js

player = document.getElementById('movie_player');
console.log(player);
console.log(player.getCurrentTime()); // ERROR IN QUESTION IS PRODUCED WITH THIS COMMAND

manifest.json

{
  "manifest_version": 2,

  "name": "It's a placeholder",
  "description": "This is only a test",
  "version": "1.0",

  "browser_action": {
    "default_popup": "popup.html",
    "default_title": "My Test"
  },

  "permissions": [
    "activeTab",
    "http://localhost/*",
    "https://www.youtube.com/*"
  ]

}
like image 725
austinmilt Avatar asked Dec 01 '16 05:12

austinmilt


1 Answers

Thanks to Charlie Dalsass (see comments below my question), I think I have an answer!

test.js

video = document.getElementsByClassName('video-stream')[0];
console.log(video);
console.log(video.currentTime);
like image 125
austinmilt Avatar answered Oct 21 '22 09:10

austinmilt