3

我正在寻找一种通过 Javascript 在嵌入式 Youtube 视频中检测播放事件的方法。现在我能够检测到状态变化,但我不知道如何在之后取消绑定事件并触发另一个事件,说它已经完成。我也不想使用 add/removeEventListener 因为我猜 IE8 及以下版本没有这个功能。

到目前为止我的代码,

    function onYouTubePlayerReady(playerId) {
    console.log('loaded');
    var ytPlayer = document.getElementById(playerId);
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
    console.log("Player's new state: " + newState);
    if(newState === 1) {
        sendYtUrl();
     }
}

function sendYtUrl() {
    console.log('play detected');
    ytplayer.removeEventListener("onStateChange");
} 

我希望弹出到 sendYtUrl,删除侦听器,然后做我需要做的任何事情,或者更好的是,保持它更清洁并将其保留在相同的功能中。

提前致谢!

4

2 回答 2

8

您无需取消绑定onStateChange事件即可知道视频何时结束或完成。onStateChange只需要有一个事件监听器。每次发生任何这些情况时,它将被触发并返回以下状态:

-1 (unstarted)
0 (ended)
1 (playing)
2 (paused)
3 (buffering)
5 (video cued)

在您的函数onytplayerStateChange中,添加另一个if语句以在视频完成时捕获:

function onytplayerStateChange(newState) {
    console.log("Player's new state: " + newState);
    if(newState === 1) {
        sendYtUrl();
    } else if(newState === 0) {
        console.log("Video has ended!");
    }
}
于 2012-10-01T16:51:29.313 回答
1

太感谢了!这让我朝着正确的方向前进。

这就是我最终做的事情。

var ytPlaying = 0;
var ytPlayed = '';
var currPlaying = '';

function onYouTubePlayerReady(playerId) {
    //console.log('loaded');
    var ytPlayer = document.getElementById(playerId);
    ytPlayer.addEventListener("onStateChange", "onytplayerStateChange");
}

function onytplayerStateChange(newState) {
    currPlaying = window.location.hash;
    //console.log("Player's new state: " + newState);
    if (newState === 1) {
        console.log('playing');
        clientSideTracking();
    }   
}


function clientSideTracking() {
   // console.log('client tracking');
    //console.log(currPlaying, ytPlayed);
    if (currPlaying != ytPlayed) { // if current playing isn't the same as prior played
        //console.log('different'); // then it's different - track it.
        var event = new AnalyticsPageEvent('Youtube Analytics', currPlaying);
        event.trigger();
    }
    ytPlaying = 0; // change back to 'not played' and change to 0 so that it's logged
    ytPlayed = currPlaying;

}

它的作用是在有尚未播放的新 URL 时触发 AnalyticPageEvent。:)

于 2012-10-01T20:00:38.740 回答