javascript - 带有 javascript 标签的 Youtube iframe API

标签 javascript api iframe youtube

我正在构建一个在线“电视”,它将为多个 channel 使用 YouTube 直播。

channel 包含在选项卡中。更改标签时需要停止视频,否则您可以在后台听到音频。

这是 JSFiddle 的链接:https://jsfiddle.net/matlow/08k4csuh/

切换到另一个 channel 时,我设法关闭了“ channel 1”:

  var iframe = document.getElementsByClassName("tvscreen")[0].contentWindow;


 iframe.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');

在标签 javascript for 循环中,它也处理 tabcontent[i].style.display = "none";
我想我需要使用for循环来调用iframe的每个实例......但我对javascript很陌生,所以我不太确定如何实现这一点。

使用 iframe.postMessage('{"event":"command","func":"playVideo","args":""}', '*'); 也会有所帮助因此,当单击相关选项卡时,视频会再次自动播放......但我又不太确定如何实现这一点。

我已经为此工作了几天,所以如果有人有任何提示或指示,我将不胜感激!

谢谢阅读! :)

最佳答案

您没有正确使用 YouTube 的 API。见 https://developers.google.com/youtube/iframe_api_reference

在你的 fiddle 中,程序化 play不可能,因为您不知道 YouTube 播放器何时准备就绪,因为您不是初始化它的人。您对 play 的尝试视频可能发生得太早了。

程序化 pause (您设法暂停了第一个视频)感谢 enablejsapi=1在 iframe src 中以及播放器此时已准备好这一事实。

这是你的 fiddle 的 fork - https://jsfiddle.net/raven0us/ancr2fgz

我添加了一些评论。检查那些。

// load YouTube iframe API as soon as possible, taken from their docs
var tag = document.createElement('script');
tag.id = 'iframe-demo';
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// initialised players are kept here so we don't have to destroy and reinit
var ytPlayers = {};

function mountChannel(channel) {
    var player;
    var iframeContainer = document.querySelectorAll('#' + channel + ' iframe');

    // if the channel & iframe we want to "mount" exist, check for playing iframes before doing anything else
    if (iframeContainer.length > 0) {
        // Object.keys() is ECMA 5+, sorry about this, but no easy to check if an object is empty
        // alternatively, you could have an array, but in that case, you won't be able to fetch a specific player as fast
        // if you don't need that functionality, array is as good cause you will just loop through active players and destroy them
        var activePlayersKeys = Object.keys(ytPlayers);
        if (activePlayersKeys.length > 0) { // if players exist in the pool, destroy them
            for (var i = 0; i < activePlayersKeys.length; i++) {
                var activeChannel = activePlayersKeys[i];
                var activePlayer = ytPlayers[activeChannel];

                activePlayer.getIframe().classList.remove('playing'); // mark pause accordingly, by removing class, not necessary
                activePlayer.pauseVideo();
            }
        }

        // check if player already initialised and if player exists, check if it has resumeVideo as a function
        if (ytPlayers.hasOwnProperty(channel)) {
            ytPlayers[channel].playVideo();
        } else {
            var iframe = iframeContainer[0];
            player = new YT.Player(iframe, {
                events: {
                    'onReady': function (event) {
                        // event.target is the YT player
                        // get the actual DOM node iframe nad mark it as playing via a class, styling purposes, not necessary
                        event.target.getIframe().classList.add('playing');
                        // play the video
                        event.target.playVideo();
                        // video may not autoplay all the time in Chrome, despite its state being cued and this event getting triggered, this happens due to a lot of factors 

                    },
                    // you should also implement `onStateChange` in order to track video state (as a result of user actions directly via YouTube controls) - https://developers.google.com/youtube/iframe_api_reference#Events
                }
            });

            // append to the list
            ytPlayers[channel] = player;
        }
    }
}

    // Get the element with id="defaultOpen" and click on it
function onYouTubeIframeAPIReady() {
    // YouTube API will call this when it's ready, only then attempt to "mount" the initial channel
    document.getElementById("defaultOpen").click();
}

这是我第一次使用 YouTube 的 iframe API,但这似乎是合理的。

关于javascript - 带有 javascript 标签的 Youtube iframe API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61416150/

相关文章:

javascript - XMLHttpRequest 没有停止

javascript/innerHTML/html

javascript - 通过 JavaScript 中的事件控制流程代码

javascript - 无法编译此 Typescript

json - 使用 API 从粉丝页面获取 Facebook 状态

php - youtube data api 3 php,如何从一个 channel 获取超过 50 个视频?

rest - Postman GET 响应二进制文件

javascript - 将 iframe 放在 HTML5 中的 canvas 元素中

html - 让网站像在智能手机上一样出现在 iframe 中?

javascript - 将用户名从 Java 发送到 iframe