2012-10-01 80 views
3

我正在尋找一種方法來檢測通過Javascript嵌入的Youtube視頻中的播放事件。現在,我可以檢測到狀態變化,但我無法弄清楚如何解除事件並解僱另一個事件,說它已完成。我也不想使用add/removeEventListener,因爲我猜IE8及以下版本沒有這個功能。在youtube api中檢測播放事件

到目前爲止我的代碼,

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,除去監聽器,然後做我需要做的,甚至更好,保持它的清潔劑,讓它在同一個函數。

在此先感謝!

回答

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

謝謝非常!這讓我朝着正確的方向發展。

這是我最終做的。

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。 :)

+0

沒問題,發佈您的解決方案+1! –

相關問題