首页 文章

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

提问于
浏览
140

我希望能够控制基于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
        }
    });
}

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

But I want to be able to operate on iframe players which are already on the page.

我可以使用旧的嵌入方法很容易地做到这一点,例如:

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

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

4 回答

  • 295

    Fiddle Links: Source code - Preview - Small version
    更新:这个小函数只能在单个方向上执行代码 . 如果你想要完全支持(例如事件监听器/ getter),看看 at Listening for Youtube Event in jQuery

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

    2012年5月17日,代码大小加倍,以便处理播放器's ready state. If you need a compact function which does not deal with the player'的就绪状态,请参阅http://jsfiddle.net/8R5y6/ .

    /**
     * @author       Rob W <gwnRob@gmail.com>
     * @website      https://stackoverflow.com/a/7513356/938089
     * @version      20131010
     * @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 / 0 = 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 (!domReady ||
                   iframe && (!iframe.contentWindow || queue && !queue.ready) ||
                   (!queue || !queue.ready) && 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");
    

    可能的问题(和答案):

    Q :它不起作用!
    A :"Doesn't work"不是一个清晰的描述 . 你收到任何错误信息吗?请出示相关代码 .

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

    Q :我收到错误消息"An invalid or illegal string was specified" . 为什么?
    A :API无法在本地主机上正常运行( file:// ) . 在线托管您的(测试)页面,或使用JSFiddle . 示例:请参阅此答案顶部的链接 .

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

    Q :支持哪些浏览器?
    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

    修订历史

    • 17 2012年5月
      已实施 onYouTubePlayerReadycallPlayer('frame_id', function() { ... }) .
      当播放器尚未准备好时,功能会自动排队 .

    • 2012年7月24日
      在支持的浏览器中更新并成功测试(展望未来) .

    • 10十月2013当函数作为参数传递时, callPlayer 强制检查准备情况 . 这是必需的,因为在文档准备好后插入iframe后立即调用 callPlayer 时,它无法确定iframe是否已完全就绪 . 在Internet Explorer和Firefox中,此方案导致过早调用 postMessage ,这被忽略 .

    • 2013年12月12日,建议在网址中添加 &origin=* .

    • 2014年3月2日,撤消了删除 &origin=* 到网址的建议 .

  • 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

  • 4

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

    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/

  • 16

    我自己的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 || []
            } ), '*');
        }
    }
    

相关问题