YouTube API - iframe onStateChange事件

时间:2014-07-07 23:23:56

标签: javascript youtube youtube-api

我正在使用iframe YouTube API,我希望跟踪事件,例如,当用户启动和停止视频时,将数据发送到Google Analytics。

<iframe src="https://www.youtube.com/embed/DjB1OvEYMhY"></iframe>

我看了https://developers.google.com/youtube/iframe_api_reference?csw=1并没有找到如何做到这一点的示例。该示例创建iframe并定义onReady和onStateChange。当我只在页面上使用iframe时,我该怎么做?

3 个答案:

答案 0 :(得分:13)

此示例使用onPlayerStateChange使用不同的states来监听用户所做的每个播放/暂停操作,并打印(记录)它们。

但是,您需要创建自己的record函数,以便根据此数据执行任何操作。

您还需要在iframe上使用ID(在本例中为 #player ),并在其网址末尾添加?enablejsapi = 1 。当然,请确保包含Youtube iframe API

注意

在代码之后声明API非常重要,因为它在准备好后会调用onYouTubeIframeAPIReady

<!DOCTYPE html>
<html>
<body>
    <iframe id="player" src="https://www.youtube.com/embed/DjB1OvEYMhY?enablejsapi=1"></iframe>
    <h5>Record of user actions:</h5>
    <script>
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player( 'player', {
          events: { 'onStateChange': onPlayerStateChange }
        });
      }
      function onPlayerStateChange(event) {
        switch(event.data) {
          case 0:
            record('video ended');
            break;
          case 1:
            record('video playing from '+player.getCurrentTime());
            break;
          case 2:
            record('video paused at '+player.getCurrentTime());
        }
      }
      function record(str){
        var p = document.createElement("p");
        p.appendChild(document.createTextNode(str));
        document.body.appendChild(p);
      }
    </script>
    <script src="https://www.youtube.com/iframe_api"></script>
</body>
</html>

JS Fiddle Demo

答案 1 :(得分:1)

这是不使用Youtubes iframe API脚本的版本。唯一的缺点是iframe API可能会更改。

<iframe id="player" src="https://www.youtube.com/embed/dQw4w9WgXcQ?enablejsapi=1"></iframe>
var addYoutubeEventListener = (function() {

    var callbacks = [];
    var iframeId = 0;

    return function (iframe, callback) {

        // init message listener that will receive messages from youtube iframes
        if(iframeId === 0) {
            window.addEventListener("message", function (e) {

                if(e.origin !== "https://www.youtube.com" || e.data === undefined) return;
                try {
                    var data = JSON.parse(e.data);
                    if(data.event !== 'onStateChange') return;

                    var callback = callbacks[data.id];
                    callback(data);
                }
                catch(e) {}
            });
        }

        // store callback
        iframeId++;
        callbacks[iframeId] = callback;
        var currentFrameId = iframeId;

        // sendMessage to frame to start receiving messages
        iframe.addEventListener("load", function () {
            var message = JSON.stringify({
                event: 'listening',
                id: currentFrameId,
                channel: 'widget'
            });
            iframe.contentWindow.postMessage(message, 'https://www.youtube.com');

            message = JSON.stringify({
                event: "command",
                func: "addEventListener",
                args: ["onStateChange"],
                id: currentFrameId,
                channel: "widget"
            });
            iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
        });
    }
})();
addYoutubeEventListener(document.getElementById("player"), function(e) {

    switch(e.info) {
        case 1:
            // playing
            break;
        case 0:
            // ended
            break;
    }
});

答案 2 :(得分:0)

有时,事件负载不足以确保iframe中的文档准备就绪。如果iframe位于其他域中,则无法订阅以查看其准备就绪时间。

一种可能的解决方法是记录从iframe收到事件的时间,如果在订阅后没有收到事件,请重试:

var addYoutubeEventListener = (function() {

   var callbacks = [];
   var iframeId = 0;
   var subscribed = [];

   return function (iframe, callback) {
       // init message listener that will receive messages from youtube iframes
       if(iframeId === 0) {
           window.addEventListener("message", function (e) {
               if(e.origin !== "https://www.youtube.com" || e.data === undefined) return;
               try {
                   var data = JSON.parse(e.data);
                   subscribed[data.id] = true;
                   if(data.event !== 'onStateChange') return;

                   var callback = callbacks[data.id];
                   callback(data);
               }
               catch(e) {}
           }, true);
       }

       // store callback
       iframeId++;
       callbacks[iframeId] = callback;
       subscribed[iframeId] = false;
       var currentFrameId = iframeId;

       //console.log("adding event listener to iframe id " + iframeId);

       // sendMessage to frame to start receiving messages
       iframe.addEventListener("load", function () {
           var tries = 0;
           var checkSubscribed = function()
           {
               if (subscribed[currentFrameId]) {
                   //console.log("subscribed succesfully " + currentFrameId)
               }
               else
               {
                   tries++;
                   //console.log("Try again " + currentFrameId + " (" + tries + ")");
                   if (tries < 100) {
                       doSubscribe();
                   }
                   else
                   {
                       console.log("Unable to subscribe" + currentFrameId );
                   }
               }
           }
           var doSubscribe = function()
           {
               var message = JSON.stringify({
                    event: 'listening',
                    id: currentFrameId,
                    channel: 'widget'
                });
                iframe.contentWindow.postMessage(message, 'https://www.youtube.com');

                message = JSON.stringify({
                    event: "command",
                    func: "addEventListener",
                    args: ["onStateChange"],
                    id: currentFrameId,
                    channel: "widget"
                });
                iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
                setTimeout(checkSubscribed, 100);
            };
            doSubscribe();
       }, true);
   }
})();