Skip to content Skip to sidebar Skip to footer

Detecting A Play Event In Youtube Api

I'm looking for a way to detect a play event in an embedded Youtube video via Javascript. Right now I'm able to detect state change, but I can't figure out how to unbind the event

Solution 1:

You don't have to unbind the onStateChange event to know when the video ends or is completed. The onStateChange only needs to have one event listener. It will be fired and return the following states every time any of these situations occur:

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

In your function onytplayerStateChange, add another if statement to catch when the video is complete:

function onytplayerStateChange(newState) {
    console.log("Player's new state: " + newState);
    if(newState === 1) {
        sendYtUrl();
    } else if(newState === 0) {
        console.log("Video has ended!");
    }
}

Solution 2:

Thank you so much! That bumped me in the right direction.

Here's what I ended up doing.

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

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

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


functionclientSideTracking() {
   // 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 = newAnalyticsPageEvent('Youtube Analytics', currPlaying);
        event.trigger();
    }
    ytPlaying = 0; // change back to 'not played' and change to 0 so that it's logged
    ytPlayed = currPlaying;

}

What it does is trigger the AnalyticPageEvent when there's a new URL that hasn't been played yet. :)

Post a Comment for "Detecting A Play Event In Youtube Api"