我尝试通过网站上现有的 iframe 来使用 YouTube API。
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/qWv6uI1lTJE" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen=""></iframe>
这是我使用的 iframe。我想用 js 添加自动播放事件和视频播放完毕时的事件。我不想创建新的 iframe,因为我使用 PHP 将 iframe 加载到我的网站中。
有人知道如何在现有的 iframe 上绑定(bind) youtube API js 吗?
感谢帮助:)
最佳答案
我找到了另一种方法,可以按照我想要的方式使用 youtube api:
您必须在网址的 和 处添加“?enablejsapi=1”。
<iframe id="player" width="560" height="315" src="https://www.youtube.com/embed/qWv6uI1lTJE?enablejsapi=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//Holds a reference to the YouTube player
var player;
//this function is called by the API
function onYouTubeIframeAPIReady() {
//creates the player object
player = new YT.Player('player');
//subscribe to events
player.addEventListener("onReady", "onYouTubePlayerReady");
player.addEventListener("onStateChange", "onYouTubePlayerStateChange");
}
function onYouTubePlayerReady(event) {
event.target.playVideo();
}
function onYouTubePlayerStateChange(event) {
switch (event.data) {
case YT.PlayerState.ENDED:
if($('#link-1').length > 0) {
var href = $('#link-1').attr('href');
window.location.href = href;
}
break;
}
}
这是我找到它的地方:https://www.htmlgoodies.com/beyond/video/respond-to-embedded-youtube-video-events.html
关于javascript - 如何在现有的 iframe 上使用 YouTube API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49052401/