如何在现有iframe上使用YouTube API?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在现有iframe上使用YouTube API?相关的知识,希望对你有一定的参考价值。

我尝试在我的网站上使用现有的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上绑定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

以上是关于如何在现有iframe上使用YouTube API?的主要内容,如果未能解决你的问题,请参考以下文章

如何启动和停止使用youtube iframe API创建的YouTube视频?

如何使用 Youtube 的 HTML5 iframe API 设置 wmode=opaque?

Youtube video iframe API - 如何在失去焦点时暂停视频?

Chromecast 上的 YouTube iframe api 行为

Youtube iframe API 无法发布消息

在 iPad 上执行 playVideo() 命令后,YouTube iFrame API 处于缓冲状态