在youtube.com上获取Youtube Video的当前时间(例如document.getElementById('movie_player').getCurrentTime())

aus*_*ilt 6 javascript youtube jquery google-chrome

我正在创建一个Google Chrome扩展程序,它依赖于了解"youtube.com"上正在播放的视频的当前时间.我知道原则上document.getElementById('movie_player').getCurrentTime()应该返回这个,但是在注入页​​面的内容脚本中调用它会产生:

未捕获的TypeError:document.getElementById('movie_player').getCurrentTime不是函数(...)

我可以在Chrome控制台中运行该命令并获得正确的返回值.

在此之前被标记为重复的问题,我想指出我正在谈论在'youtube.com'上这样做.我不知道我是否应该期待特殊行为,但这绝对是与我在stackoverflow上发现的其他问题不同的背景.

为了提供帮助,下面是我能想出的最简单的代码来重现这个问题.要使其正常工作,您需要将其作为解压扩展加载.然后导航到任何YouTube视频.单击扩展图标,然后单击"开始测试"按钮.还要确保打开控制台(F12).

提前感谢有关如何使此方法工作的建议,或者我可以获得我需要的信息的另一种方式(例如,我考虑获得时间价值的份额,但无法想出那个方法).作为最后的手段,我正在考虑用我自己的iframe替换youtube播放器并尝试这种方式.

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>
Run Code Online (Sandbox Code Playgroud)

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'});
}
Run Code Online (Sandbox Code Playgroud)

test.js

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

的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/*"
  ]

}
Run Code Online (Sandbox Code Playgroud)

aus*_*ilt 5

感谢 Charlie Dalsass(请参阅我的问题下面的评论),我想我有了答案!

测试.js

video = document.getElementsByClassName('video-stream')[0];
console.log(video);
console.log(video.currentTime);
Run Code Online (Sandbox Code Playgroud)