我正在创建一个 Google Chrome 扩展程序,它依赖于了解“youtube.com”上正在播放的视频的当前时间。我知道,原则上,document.getElementById('movie_player').getCurrentTime()
应该返回这个,但是在注入(inject)页面的内容脚本中调用它会产生:
Uncaught TypeError: document.getElementById('movie_player').getCurrentTime is not a function(…)
我能够在 Chrome 控制台中运行该命令并获得正确的返回值。
在将此问题标记为重复问题之前,我想指出我是在“youtube.com”上谈论这样做。我不知道我是否应该期待特殊行为,但这绝对与我在 stackoverflow 上发现的其他问题不同。
为了提供帮助,下面是我可以想出的最简单的代码来重现这个问题。要使其正常工作,您需要 load this as an unpacked extension .然后导航到任何 youtube 视频。单击扩展图标,然后单击“开始测试”按钮。还要确保您已打开控制台 (F12)。
预先感谢有关如何使此方法起作用的建议,或我可以获得所需信息的其他方法(例如,我研究过按时间值(value)获取份额,但无法弄清楚)。作为最后的手段,我正在考虑用我自己的 iframe 替换 youtube 播放器并尝试这种方式。
弹出窗口
<!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>
弹出窗口
// 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'});
}
测试.js
player = document.getElementById('movie_player');
console.log(player);
console.log(player.getCurrentTime()); // ERROR IN QUESTION IS PRODUCED WITH THIS COMMAND
list .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/*"
]
}
最佳答案
感谢 Charlie Dalsass(请参阅我的问题下方的评论),我想我找到了答案!
测试.js
video = document.getElementsByClassName('video-stream')[0];
console.log(video);
console.log(video.currentTime);
关于javascript - 在 youtube.com 上获取 Youtube 视频的当前时间(例如 document.getElementById ('movie_player').getCurrentTime()),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40903317/