用 JavaScript 或 jQuery 监听 Youtube 事件

IT技术 javascript jquery events youtube youtube-api
2021-01-25 07:51:06

我有一个滑块,其中包含 4 个通过 iframe 嵌入代码嵌入的 youtube 视频

http://www.youtube.com/embed/'.$i.'?enablejsapi=1

我试图让onStateChange四个视频中的任何一个事件调用我调用的函数,该函数stopCycle()将在视频开始播放时停止滑块。iframe 没有 ID。我不确定如何正确捕获此事件,并且可以使用任何关于我做错了什么的建议。

<script charset="utf-8" type="text/javascript" src="http://www.youtube.com/player_api"></script>

var playerObj = document.getElementById("tab2"); // the container for 1 of the 4 iframes

playerObj.addEventListener("onStateChange", "stopCycle");

function stopCycle(event) {
    alert('Stopped!');
}
4个回答

YouTube的框架API 支持现有的框架为了改进使用,我创建了一些辅助函数。看看下面的代码+评论和演示:http : //jsfiddle.net/YzvXa/197

要将函数绑定到现有框架,您必须将 ID 引用传递给框架。在您的情况下,框架包含在带有id="tab2". 我定义了一个自定义函数,以便于实现:

function getFrameID(id){
    var elem = document.getElementById(id);
    if (elem) {
        if(/^iframe$/i.test(elem.tagName)) return id; //Frame, OK
        // else: Look for frame
        var elems = elem.getElementsByTagName("iframe");
        if (!elems.length) return null; //No iframe found, FAILURE
        for (var i=0; i<elems.length; i++) {
           if (/^https?:\/\/(?:www\.)?youtube(?:-nocookie)?\.com(\/|$)/i.test(elems[i].src)) break;
        }
        elem = elems[i]; //The only, or the best iFrame
        if (elem.id) return elem.id; //Existing ID, return it
        // else: Create a new ID
        do { //Keep postfixing `-frame` until the ID is unique
            id += "-frame";
        } while (document.getElementById(id));
        elem.id = id;
        return id;
    }
    // If no element, return null.
    return null;
}

// Define YT_ready function.
var YT_ready = (function() {
    var onReady_funcs = [], api_isReady = false;
    /* @param func function     Function to execute on ready
     * @param func Boolean      If true, all qeued functions are executed
     * @param b_before Boolean  If true, the func will added to the first
                                 position in the queue*/
    return function(func, b_before) {
        if (func === true) {
            api_isReady = true;
            while (onReady_funcs.length) {
                // Removes the first func from the array, and execute func
                onReady_funcs.shift()();
            }
        } else if (typeof func == "function") {
            if (api_isReady) func();
            else onReady_funcs[b_before?"unshift":"push"](func); 
        }
    }
})();
// This function will be called when the API is fully loaded
function onYouTubePlayerAPIReady() {YT_ready(true)}

// Load YouTube Frame API
(function() { // Closure, to not leak to the scope
  var s = document.createElement("script");
  s.src = (location.protocol == 'https:' ? 'https' : 'http') + "://www.youtube.com/player_api";
  var before = document.getElementsByTagName("script")[0];
  before.parentNode.insertBefore(s, before);
})();

//以前,定义了核心功能。展望实施:

var player; //Define a player object, to enable later function calls, without
            // having to create a new class instance again.

// Add function to execute when the API is ready
YT_ready(function(){
    var frameID = getFrameID("tabs2");
    if (frameID) { //If the frame exists
        player = new YT.Player(frameID, {
            events: {
                "onStateChange": stopCycle
            }
        });
    }
});

// Example: function stopCycle, bound to onStateChange
function stopCycle(event) {
    alert("onStateChange has fired!\nNew state:" + event.data);
}

如果您想稍后调用其他功能,例如将视频静音,请使用:

player.mute();
  • 如果您只需要调用简单的单向函数,则没有必要使用此代码。相反,请使用此答案中callPlayer定义的函数
  • 如果您想同时多个帧实现此功能,请查看此答案还包括对getFrameID的详细解释YT_ready
@DaveKiss 如果 IFrame 是使用 YouTube Frame API 动态生成的,您可以查看第二个链接。否则,您必须稍等,因为尚未实现双向事件侦听器。我正在努力。
2021-03-19 07:51:06
实现该功能后,您可以更新此问题吗?
2021-03-30 07:51:06
你能举例说明我需要做什么才能在我的场景中使用该功能吗?
2021-03-31 07:51:06
@absynthemindwebsmith 使用 -if语句,例如:if (event.data == -1) return;
2021-03-31 07:51:06
@RobW 我在我的原始问题中提供了一个示例,因此您可以看到我正在尝试做什么 - 基本上是在单击自定义缩略图时启动视频。这是我对未来访问者的问题的链接 - stackoverflow.com/questions/8948403/...
2021-04-10 07:51:06

您可以使用tubeplayer插件,它带有许多要侦听的事件。

我的 iframe 无法动态生成,它们是通过 php 创建的。
2021-04-02 07:51:06

从昨天开始,这不再起作用了。onStateChange 不会被触发。杰弗里发布了一个快速修复,但我无法更新上述答案

有关此问题的更多信息https://code.google.com/p/gdata-issues/issues/detail?id=4706

得到它的工作:-) 与修复

添加以下功能

function onReady() {
    player.addEventListener('onStateChange', function(e) {
        console.log('State is:', e.data);
    });
}

在 "onStateChange": stopCycle 之前添加 "onReady": onReady,

我的聊天中有这个功能,让用户可以从 youtube 上发布视频。vid 的 url 附加为带有 id 的现有 iframe 的来源。

我注意到的是 - 尽管添加了 ?enablejsapi=1 - 该脚本仅适用于页面加载时现有的 iframe。

在为 iframe 设置新源后希望绑定此脚本时,将如何进行?