【发布时间】:2019-10-19 17:46:25
【问题描述】:
我需要获取我在 iFrame 中播放的 youtube 视频的当前时间,但无法从我的脚本中访问该视频。
在浏览器开发工具中选择视频后,我可以毫无问题地使用console.alert($("#player").children[0].getCurrentTime())。
但是,当从脚本运行相同的代码时,我会得到 TypeError: Cannot read property 'getCurrentTime' of undefined。
This 在 SO 上的帖子让我认为这与未打开开发工具时隐藏的元素有关。但是$("#player").children[0].removeClass("hidden") 返回TypeError: $(...).contents is not a function at <anonymous>。该元素似乎不存在。
以下是完整代码,其中 90% 直接来自第一个 iframe 示例 here。
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'U03lLvhBzOw',
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
console.alert($("#player").children[0].getCurrentTime()) //DOESN'T WORK
}
</script>
</body>
</html>
【问题讨论】:
标签: javascript jquery iframe youtube-iframe-api