我正在寻找一种通过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,删除监听器,然后做我需要做的事情,或者甚至更好,保持清洁并将其留在同一个功能中。
提前致谢!
答案 0 :(得分:8)
您无需取消绑定onStateChange
event即可知道视频何时结束或已完成。 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!");
}
}
答案 1 :(得分: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;
}
当有一个尚未播放的新网址时,它会触发AnalyticPageEvent。 :)