【问题标题】:How to use YouTube API on existing iframe?如何在现有 iframe 上使用 YouTube API?
【发布时间】:2018-08-09 16:20:53
【问题描述】:

我尝试通过我网站上现有的 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?

感谢帮助:)

【问题讨论】:

    标签: javascript api iframe youtube youtube-api


    【解决方案1】:

    我找到了另一种方式,我可以随意使用 youtube api:

    您必须在 url 的 and 处添加“?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

    【讨论】:

      猜你喜欢
      • 2014-03-07
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 2011-06-24
      • 2011-12-07
      • 1970-01-01
      相关资源
      最近更新 更多