程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了YouTube iframe API:如何控制HTML中已经存在的iframe播放器?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

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

开发过程中遇到YouTube iframe API:如何控制HTML中已经存在的iframe播放器?的问题如何解决?下面主要结合日常开发的经验,给出你关于YouTube iframe API:如何控制HTML中已经存在的iframe播放器?的解决方法建议,希望对你解决YouTube iframe API:如何控制HTML中已经存在的iframe播放器?有所启发或帮助;

更新:此小功能将仅在单个方向上执行代码。

经过深入的代码分析,我创建了一个函数:functioncallPlayer在任何带框架的YouTube视频上请求一个函数调用。

代码大小增加了一倍,以照顾玩家的就绪状态。如果您需要一个不处理播放器就绪状态的紧凑功能,请参见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");

可能的问题(和答案):

:这不起作用! :“不起作用”的描述不明确。您收到任何错误消息吗?请显示相关代码。

playVIDeo不播放视频。 :播放需要用户互动以及allow="autoplay"iframe上的存在。

:我已经使用嵌入了YouTube视频,<iframesrc="http://www.youtube.com/embed/As2rZGPGKDY" />但是该功能没有执行任何功能! :您必须?enableJsAPI=1在URL末尾添加/embed/vID_ID?enableJsAPI=1

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

:您怎么知道的? :我花了一些时间来手动解释API的来源。我得出的结论是我必须使用该postmessage方法。为了知道要传递哪些参数,我创建了一个Chrome扩展程序来拦截消息。扩展的源代码可以在这里下载。

:支持哪些浏览器? :每个支持JSON和的浏览器postmessage

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

修订记录

  • 于2012年5月17日 实施onYouTubePlayerReadycallPlayer('frame_ID', function() { ... })。 播放器尚未准备就绪时,功能会自动排队。

  • 2012年7月24日, 更新并在受支持的浏览器中进行了成功测试(请注意)。

  • 2013年10月10日当函数作为参数传递时,callPlayer强制检查准备情况。这是必需的,因为在callPlayer文档准备就绪后,在插入iframe之后立即调用时,无法确定iframe是否已完全准备就绪。在Internet Explorer和firefox中,这种情况导致的调用太早postmessage,被忽略了。

  • 2013年12月12日,建议添加&origin=*URL。
  • 2014年3月2日,撤消了删除&origin=*该URL的建议。
  • 2019年4月9日,修复了在页面准备就绪之前加载YouTube时导致无限递归的错误。添加有关自动播放的注释。

解决方法

我希望能够控制基于iframe的YouTube播放器。该播放器已经存在于HTML中,但是我想通过JavaScript API对其进行控制。

我一直在阅读iframeAPI的文档,其中解释了如何使用API​​向页面添加新视频,然后使用YouTube播放器功能对其进行控制:

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

该代码创建了一个新的播放器对象,并将其分配给“player”,然后将其插入#containerdiv中。然后,我可以在“播放器”和呼叫操作playVideo()pauseVideo()就可以了,等等。

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

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

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

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

大佬总结

以上是大佬教程为你收集整理的YouTube iframe API:如何控制HTML中已经存在的iframe播放器?全部内容,希望文章能够帮你解决YouTube iframe API:如何控制HTML中已经存在的iframe播放器?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。