YouTube iframe API:如何控制已经在HTML中的iframe播放器?

时间:2011-09-16 10:49:39

标签: javascript youtube-api youtube-javascript-api

我希望能够控制基于iframe的YouTube播放器。这些播放器已经在HTML中,但我希望通过JavaScript API控制它们。

我一直在阅读documentation for the iframe API,其中介绍了如何使用API​​向页面添加新视频,然后使用YouTube播放器功能对其进行控制:

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('container', {
        height: '390',
        width: '640',
        videoId: 'u1zgFlCw8Aw',
        events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
        }
    });
}

该代码创建一个新的播放器对象并将其分配给“播放器”,然后将其插入#container div中。然后,我可以对“播放器”进行操作,并在其上调用playVideo()pauseVideo()等。

但我希望能够对页面上已有的iframe播放器进行操作。

我可以使用旧的嵌入方法轻松完成此操作,例如:

player = getElementById('whateverID');
player.playVideo();

但这不适用于新的iframe。如何在页面上分配iframe对象,然后在其上使用API​​函数?

7 个答案:

答案 0 :(得分:297)

小提琴链接:Source code - Preview - Small version
更新:这个小函数只能在单个方向上执行代码。如果您需要完全支持(例如,事件监听/吸气者),请查看 Listening for Youtube Event in jQuery

作为深度代码分析的结果,我创建了一个功能:function callPlayer请求对任何带框的YouTube视频进行功能调用。请参阅YouTube Api reference以获取可能的函数调用的完整列表。阅读源代码中的注释以获得解释。

2012年5月17日,代码大小加倍,以便照顾玩家的就绪状态。如果您需要一个不处理播放器就绪状态的紧凑功能,请参阅http://jsfiddle.net/8R5y6/

/**
 * @author       Rob W <gwnRob@gmail.com>
 * @website      https://stackoverflow.com/a/7513356/938089
 * @version      20190409
 * @description  Executes function on a framed YouTube video (see website link)
 *               For a full list of possible functions, see:
 *               https://developers.google.com/youtube/js_api_reference
 * @param String frame_id The id of (the div containing) the frame
 * @param String func     Desired function to call, eg. "playVideo"
 *        (Function)      Function to call when the player is ready.
 * @param Array  args     (optional) List of arguments to pass to function func*/
function callPlayer(frame_id, func, args) {
    if (window.jQuery && frame_id instanceof jQuery) frame_id = frame_id.get(0).id;
    var iframe = document.getElementById(frame_id);
    if (iframe && iframe.tagName.toUpperCase() != 'IFRAME') {
        iframe = iframe.getElementsByTagName('iframe')[0];
    }

    // When the player is not ready yet, add the event to a queue
    // Each frame_id is associated with an own queue.
    // Each queue has three possible states:
    //  undefined = uninitialised / array = queue / .ready=true = ready
    if (!callPlayer.queue) callPlayer.queue = {};
    var queue = callPlayer.queue[frame_id],
        domReady = document.readyState == 'complete';

    if (domReady && !iframe) {
        // DOM is ready and iframe does not exist. Log a message
        window.console && console.log('callPlayer: Frame not found; id=' + frame_id);
        if (queue) clearInterval(queue.poller);
    } else if (func === 'listening') {
        // Sending the "listener" message to the frame, to request status updates
        if (iframe && iframe.contentWindow) {
            func = '{"event":"listening","id":' + JSON.stringify(''+frame_id) + '}';
            iframe.contentWindow.postMessage(func, '*');
        }
    } else if ((!queue || !queue.ready) && (
               !domReady ||
               iframe && !iframe.contentWindow ||
               typeof func === 'function')) {
        if (!queue) queue = callPlayer.queue[frame_id] = [];
        queue.push([func, args]);
        if (!('poller' in queue)) {
            // keep polling until the document and frame is ready
            queue.poller = setInterval(function() {
                callPlayer(frame_id, 'listening');
            }, 250);
            // Add a global "message" event listener, to catch status updates:
            messageEvent(1, function runOnceReady(e) {
                if (!iframe) {
                    iframe = document.getElementById(frame_id);
                    if (!iframe) return;
                    if (iframe.tagName.toUpperCase() != 'IFRAME') {
                        iframe = iframe.getElementsByTagName('iframe')[0];
                        if (!iframe) return;
                    }
                }
                if (e.source === iframe.contentWindow) {
                    // Assume that the player is ready if we receive a
                    // message from the iframe
                    clearInterval(queue.poller);
                    queue.ready = true;
                    messageEvent(0, runOnceReady);
                    // .. and release the queue:
                    while (tmp = queue.shift()) {
                        callPlayer(frame_id, tmp[0], tmp[1]);
                    }
                }
            }, false);
        }
    } else if (iframe && iframe.contentWindow) {
        // When a function is supplied, just call it (like "onYouTubePlayerReady")
        if (func.call) return func();
        // Frame exists, send message
        iframe.contentWindow.postMessage(JSON.stringify({
            "event": "command",
            "func": func,
            "args": args || [],
            "id": frame_id
        }), "*");
    }
    /* IE8 does not support addEventListener... */
    function messageEvent(add, listener) {
        var w3 = add ? window.addEventListener : window.removeEventListener;
        w3 ?
            w3('message', listener, !1)
        :
            (add ? window.attachEvent : window.detachEvent)('onmessage', listener);
    }
}

用法:

callPlayer("whateverID", function() {
    // This function runs once the player is ready ("onYouTubePlayerReady")
    callPlayer("whateverID", "playVideo");
});
// When the player is not ready yet, the function will be queued.
// When the iframe cannot be found, a message is logged in the console.
callPlayer("whateverID", "playVideo");

可能的问题(&amp;答案):

:它不起作用!
A :“不起作用”不是一个明确的描述。你收到任何错误信息吗?请出示相关代码。

playVideo无法播放视频 A :播放需要用户互动,并且iframe上存在allow="autoplay"。请参阅https://developers.google.com/web/updates/2017/09/autoplay-policy-changeshttps://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide

:我使用<iframe src="http://www.youtube.com/embed/As2rZGPGKDY" />嵌入了YouTube视频,但该功能未执行任何功能!
A :您必须在网址末尾添加?enablejsapi=1/embed/vid_id?enablejsapi=1

:我收到错误消息“指定了无效或非法的字符串”。为什么呢?
A :API无法在本地主机(file://)上正常运行。在线托管您的(测试)页面,或使用JSFiddle。示例:请参阅此答案顶部的链接。

:你是怎么知道的? A :我花了一些时间来手动解释API的来源。我总结说我必须使用postMessage方法。要知道要传递哪些参数,我创建了一个拦截邮件的Chrome扩展程序。可以下载扩展程序的源代码here

:支持哪些浏览器?
A :支持JSONpostMessage的每个浏览器。

  • IE 8 +
  • Firefox 3.6+(实际上是3.5,但document.readyState已在3.6)
  • 中实施
  • Opera 10.50 +
  • Safari 4 +
  • Chrome 3 +

相关答案/实施:Fade-in a framed video using jQuery
完整的API支持:Listening for Youtube Event in jQuery
官方API:https://developers.google.com/youtube/iframe_api_reference

修订历史

  • 2012年5月17日 已实施onYouTubePlayerReadycallPlayer('frame_id', function() { ... }) 当播放器尚未准备就绪时,功能会自动排队。
  • 2012年7月24日
    在支持的浏览器中更新并成功测试(展望未来)。
  • 2013年10月10日 当函数作为参数传递时,callPlayer会强制检查准备情况。这是必需的,因为在文档准备好后插入iframe后立即调用callPlayer时,它无法确定iframe是否已完全就绪。在Internet Explorer和Firefox中,此方案导致对postMessage的过早调用,这被忽略。
  • 2013年12月12日,建议在网址中添加&origin=*
  • 2014年3月2日,撤消了将&origin=*移至网址的建议。
  • 2019年4月9日,修复了在页面准备好之前加载YouTube时导致无限递归的错误。添加关于自动播放的说明。

答案 1 :(得分:31)

看起来YouTube已经更新了他们的JS API,所以默认情况下这是可用的!您可以使用现有的YouTube iframe ID ...

<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>

...在你的JS ......

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    events: {
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerStateChange() {
  //...
}

...构造函数将使用您现有的iframe,而不是用新的iframe替换它。这也意味着您不必将videoId指定给构造函数。

请参阅Loading a video player

答案 2 :(得分:16)

您可以使用更少的代码执行此操作:

function callPlayer(func, args) {
    var i = 0,
        iframes = document.getElementsByTagName('iframe'),
        src = '';
    for (i = 0; i < iframes.length; i += 1) {
        src = iframes[i].getAttribute('src');
        if (src && src.indexOf('youtube.com/embed') !== -1) {
            iframes[i].contentWindow.postMessage(JSON.stringify({
                'event': 'command',
                'func': func,
                'args': args || []
            }), '*');
        }
    }
}

工作示例: http://jsfiddle.net/kmturley/g6P5H/296/

答案 3 :(得分:4)

上面我自己的Kim T代码版本与一些jQuery结合,允许定位特定的iframe。

$(function() {
    callPlayer($('#iframe')[0], 'unMute');
});

function callPlayer(iframe, func, args) {
    if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
        iframe.contentWindow.postMessage( JSON.stringify({
            'event': 'command',
            'func': func,
            'args': args || []
        } ), '*');
    }
}

答案 4 :(得分:1)

我在上面的例子中遇到了问题,所以相反,我只是在源代码中插入带有自动播放的 JS 的 iframe,它对我来说很好用。我还可以使用 Vimeo 或 YouTube,因此我需要能够处理这些问题。

这个解决方案并不神奇,可以清理,但这对我有用。我也不喜欢 jQuery,但该项目已经在使用它,我只是重构现有代码,随时清理或转换为 vanilla JS :)

<!-- HTML -->
<div class="iframe" data-player="viemo" data-src="$PageComponentVideo.VideoId"></div>


<!-- jQuery -->
$(".btnVideoPlay").on("click", function (e) {
        var iframe = $(this).parents(".video-play").siblings(".iframe");
        iframe.show();

        if (iframe.data("player") === "youtube") {
            autoPlayVideo(iframe, iframe.data("src"), "100%", "100%");
        } else {
            autoPlayVideo(iframe, iframe.data("src"), "100%", "100%", true);
        }
    });

    function autoPlayVideo(iframe, vcode, width, height, isVimeo) {
        if (isVimeo) {
            iframe.html(
                '<iframe width="' +
                    width +
                    '" height="' +
                    height +
                    '" src="https://player.vimeo.com/video/' +
                    vcode +
                    '?color=ff9933&portrait=0&autoplay=1" frameborder="0" allowfullscreen wmode="Opaque"></iframe>'
            );
        } else {
            iframe.html(
                '<iframe width="' +
                    width +
                    '" height="' +
                    height +
                    '" src="https://www.youtube.com/embed/' +
                    vcode +
                    '?autoplay=1&loop=1&rel=0&wmode=transparent" frameborder="0" allowfullscreen wmode="Opaque"></iframe>'
            );
        }
    }

答案 5 :(得分:0)

谢谢Rob W的回答。

我一直在Cordova应用程序中使用它,以避免必须加载API,因此我可以轻松控制动态加载的iframe。

我一直希望能够从iframe中提取信息,例如状态(getPlayerState)和时间(getCurrentTime)。

Rob W帮助突出了使用postMessage的API的工作原理,但是当然,这仅从一个方向将信息从我们的网页发送到iframe。访问吸气剂需要我们监听从iframe发回给我们的消息。

我花了一些时间弄清楚如何调整Rob W的答案来激活和收听iframe返回的消息。我基本上是在YouTube iframe中搜索源代码,直到找到负责发送和接收消息的代码。

关键是将“事件”更改为“侦听”,这基本上可以访问所有旨在返回值的方法。

以下是我的解决方案,请注意,只有在要求使用吸气剂时,我才切换到“监听”,您可以调整条件以包括其他方法。

请进一步注意,您可以通过将console.log(e)添加到window.onmessage中来查看从iframe发送的所有消息。您会注意到,一旦激活收听功能,您将收到不断更新的信息,其中包括视频的当前时间。调用诸如getPlayerState之类的吸气剂将激活这些不断的更新,但仅在状态改变后才发送涉及视频状态的消息。

function callPlayer(iframe, func, args) {
    iframe=document.getElementById(iframe);
    var event = "command";
    if(func.indexOf('get')>-1){
        event = "listening";
    }

    if ( iframe&&iframe.src.indexOf('youtube.com/embed') !== -1) {
      iframe.contentWindow.postMessage( JSON.stringify({
          'event': event,
          'func': func,
          'args': args || []
      }), '*');
    }
}
window.onmessage = function(e){
    var data = JSON.parse(e.data);
    data = data.info;
    if(data.currentTime){
        console.log("The current time is "+data.currentTime);
    }
    if(data.playerState){
        console.log("The player state is "+data.playerState);
    }
}

答案 6 :(得分:0)

一个快速解决方案,如果请求不是问题,并且您希望这种行为用于显示/隐藏视频之类的东西,是删除/添加 iframe,或清理和填充src

const stopPlayerHack = (iframe) => {
    let src = iframe.getAttribute('src');
    iframe.setAttribute('src', '');
    iframe.setAttribute('src', src);
}

iframe 将被移除,停止播放,之后将立即加载。就我而言,我已经改进了代码,以便在打开灯箱时再次在线设置 src,因此只有在用户要求观看视频时才会加载。