Skip to content

Instantly share code, notes, and snippets.

@rxnlabs
Last active August 29, 2015 14:02
Show Gist options
  • Save rxnlabs/58c09420d8e63e8419c5 to your computer and use it in GitHub Desktop.
Save rxnlabs/58c09420d8e63e8419c5 to your computer and use it in GitHub Desktop.
Javascript - Add Google Analytics event tracking to youtube player
<script src="/link-to-youtube-ga-event-tracking-javascript-code.js"></script>
<!--IFRAME CODE FOR YOUTUBE PLAYLIST PLAYER-->
<div id="oil_gas_training">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
var tag=document.createElement("script");
tag.src="//www.youtube.com/iframe_api";
var firstScriptTag=document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag,firstScriptTag);
var ytplayer;
function onYouTubeIframeAPIReady(){
ytplayer=new YT.Player("oil_gas_training",{
height:"264",
width:"425",
playerVars:{
listType:"playlist",
list:"PLpNeu1p03wKZmfXcC415TXK3CACSzr2KS"
},
events:{
onReady:onYouTubePlayerIframeReady,
onStateChange:onYouTubePlayerIframeStateChange
}
})
};
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/swfobject/2.2/swfobject.js"></script>
<!--JAVASCRIPT CODE YOUTUBE PLAYER-->
<div id="ncst_virtual_tour">
You need Flash player 8+ and JavaScript enabled to view this video.
</div>
<script type="text/javascript">
var params = { allowScriptAccess: "always" };
var atts = { id: "ncst_virtual_tour" };
swfobject.embedSWF("http://www.youtube.com/v/ohZOoSMyki8?enablejsapi=1&amp;playerapiid=ncst_virtual_tour&amp;version=3","ncst_virtual_tour", "465", "264", "8", null, null, params, atts);
</script>
function onYouTubePlayerReady(playerId){
ytplayer = document.getElementById(playerId);
if (ytplayer.addEventListener) { // W3C DOM
ytplayer.addEventListener("onStateChange", "onYouTubePlayerStateChange");
}
else if (ytplayer.attachEvent) { // IE DOM
ytplayer.attachEvent("onStateChange", "onYouTubePlayerStateChange");
}
//get the total video time mius 1 so we can account for the time difference of the paused and eded state so the pause state doesn't fire when we reach the end of the video
yt_video_total_time = ytplayer.getDuration() - 1;
}
function onYouTubePlayerIframeReady(event){
yt_video_total_time = ytplayer.getDuration() - 1;
}
//create a variable that counts how many times the video has been paused to make sure multiple events are being sent to Analytics based on current state of player. I only want to count uinque events once per player interaction
var yt_player_buffer = false;
var yt_player_play = false;
var yt_player_pause = false;
var yt_player_ended = false;
var yt_player_fast_forward = false;
var yt_player_rewind = false;
//define variables to help define custom events/states
var replay_video = null;
var play_once = false;
var current_state_pause = null;
var curr_yt_player_state = null;
var yt_video_total_time = null;
//create more variables to fast forwards and rewinds in order to send both rewinds and fast forwards to GA for per interaction
var fast_forward_once = false;
var fast_forward_once = false;
var previous_state = null;
//possible player states. Naming based https://developers.google.com/youtube/js_api_reference#Events
var unstarted_state = "Unstarted";
var buffer_state = "Buffering";
var play_state = "Playing";
var pause_state = "Paused";
var end_state = "Ended";
var video_cued_state = "Video Cued";
var replay_state = "Replay";
var fast_forward_state = "Fast Forward";
var rewind_state = "Rewind";
function onYouTubePlayerIframeStateChange(ytplayer_state){
switch( ytplayer_state.data){
case -1: curr_yt_player_state = unstarted_state;
break;
case 0: curr_yt_player_state = end_state;
break;
case 1: curr_yt_player_state = play_state;
break;
case 2: curr_yt_player_state = pause_state;
break;
case 3: curr_yt_player_state= buffer_state;
break;
case 5: curr_yt_player_state = video_cued_state;
break;
default:
}
//check if the video has been replayed. If so, reset all of the count variables to "false" so we can recount all interactions. If you replay video, the next state after ended is "playing" or "buffering" depending on video size or network speed.
if ( (replay_video === end_state && curr_yt_player_state === buffer_state) || (replay_video === end_state && curr_yt_player_state === play_state) ){
yt_player_buffer = yt_player_play = yt_player_pause = yt_player_ended = yt_player_fast_forward = yt_player_rewind = play_once = false;
current_state_pause = null;
//send the action "replay" to GA
_gaq.push(['_trackEvent','YouTube Video',replay_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl() ,0,true]);
//reset the replay_video variable so we aren't running this again until the player is reset
replay_video = null;
}
if( typeof curr_yt_player_state != "null" ){
var actual_time = ytplayer.getCurrentTime();
var elapsed_seconds = Math.ceil( actual_time );
if( curr_yt_player_state === unstarted_state ){
_gaq.push(['_trackEvent','YouTube Video',unstarted_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),0,true]);
}
else if( curr_yt_player_state === buffer_state && yt_player_buffer === false ){
_gaq.push(['_trackEvent','YouTube Video',buffer_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(), 0, true]);
yt_player_buffer = true;
}
else if( curr_yt_player_state === play_state ){
//only send the play event to GA one time per video interaction
if( yt_player_play === false ){
_gaq.push(['_trackEvent','YouTube Video',play_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),0,true]);
}
previous_state = curr_yt_player_state;
var current_time = ytplayer.getCurrentTime();
//get the time difference between when video was paused and when it was played again
var pause_play_difference = current_time - current_state_pause;
elapsed_seconds = Math.abs( Math.ceil( pause_play_difference ) );
if( typeof current_state_pause === "number" ){
//only send Fast Forward event to GA if the time difference is greater than 2 and same for a rewind
if( pause_play_difference >= 2 && yt_player_fast_forward === false ){
_gaq.push(['_trackEvent','YouTube Video',fast_forward_state, location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),elapsed_seconds,true]);
yt_player_fast_forward = true;
play_count++;
}
if( pause_play_difference <= -2 && yt_player_rewind === false ){
_gaq.push(['_trackEvent','YouTube Video',rewind_state, location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),elapsed_seconds,true]);
yt_player_rewind = true;
play_count++;
}
}
yt_player_play = true;
}
else if( curr_yt_player_state === pause_state ){
//send GA event this way so I can track Fast Forward and Rewind one time
if( yt_player_pause === false ){
if( actual_time < yt_video_total_time ){
_gaq.push(['_trackEvent','YouTube Video',pause_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(), elapsed_seconds,true]);
yt_player_pause = true;
}
}
//fast forward and rewind only work when the user pauses the video and then jumps ahead. it doesn't work if this user just skips into the video since the pause state is always before the play state, the time that the play state takes place, would always be greater
if( previous_state != pause_state && ( yt_player_fast_forward === false || yt_player_rewind === false) ){
//grab the time that the video was paused
current_state_pause = ytplayer.getCurrentTime();
}
//make the previous state pause since this allows us to determine if paused was sent multiple times in a row
previous_state = curr_yt_player_state;
}
else if( curr_yt_player_state === end_state && yt_player_ended === false ){
_gaq.push(['_trackEvent','YouTube Video',end_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),0,true]);
yt_player_ended = true;
//set the replay_video variable to "ended" so we can track if the video was replayed
replay_video = end_state;
}
}
}
function onYouTubePlayerStateChange(ytplayer_state){
switch( ytplayer_state){
case -1: curr_yt_player_state = unstarted_state;
break;
case 0: curr_yt_player_state = end_state;
break;
case 1: curr_yt_player_state = play_state;
break;
case 2: curr_yt_player_state = pause_state;
break;
case 3: curr_yt_player_state= buffer_state;
break;
case 5: curr_yt_player_state = video_cued_state;
break;
default:
}
//check if the video has been replayed. If so, reset all of the count variables to "false" so we can recount all interactions. If you replay video, the next state after ended is "playing" or "buffering" depending on video size or network speed.
if ( (replay_video === end_state && curr_yt_player_state === buffer_state) || (replay_video === end_state && curr_yt_player_state === play_state) ){
yt_player_buffer = yt_player_play = yt_player_pause = yt_player_ended = yt_player_fast_forward = yt_player_rewind = play_once = false;
current_state_pause = null;
//send the action "replay" to GA
_gaq.push(['_trackEvent','YouTube Video',replay_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl() ,0,true]);
//reset the replay_video variable so we aren't running this again until the player is reset
replay_video = null;
}
if( typeof curr_yt_player_state != "null" ){
var actual_time = ytplayer.getCurrentTime();
var elapsed_seconds = Math.ceil( actual_time );
if( curr_yt_player_state === unstarted_state ){
_gaq.push(['_trackEvent','YouTube Video',unstarted_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),0,true]);
}
else if( curr_yt_player_state === buffer_state && yt_player_buffer === false ){
_gaq.push(['_trackEvent','YouTube Video',buffer_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(), 0, true]);
yt_player_buffer = true;
}
else if( curr_yt_player_state === play_state ){
//only send the play event to GA one time per video interaction
if( yt_player_play === false ){
_gaq.push(['_trackEvent','YouTube Video',play_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),0,true]);
}
previous_state = curr_yt_player_state;
var current_time = ytplayer.getCurrentTime();
//get the time difference between when video was paused and when it was played again
var pause_play_difference = current_time - current_state_pause;
elapsed_seconds = Math.abs( Math.ceil( pause_play_difference ) );
if( typeof current_state_pause === "number" ){
//only send Fast Forward event to GA if the time difference is greater than 2 and same for a rewind
if( pause_play_difference >= 2 && yt_player_fast_forward === false ){
_gaq.push(['_trackEvent','YouTube Video',fast_forward_state, location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),elapsed_seconds,true]);
yt_player_fast_forward = true;
play_count++;
}
if( pause_play_difference <= -2 && yt_player_rewind === false ){
_gaq.push(['_trackEvent','YouTube Video',rewind_state, location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),elapsed_seconds,true]);
yt_player_rewind = true;
play_count++;
}
}
yt_player_play = true;
}
else if( curr_yt_player_state === pause_state ){
//send GA event this way so I can track Fast Forward and Rewind one time
if( yt_player_pause === false ){
if( actual_time < yt_video_total_time ){
_gaq.push(['_trackEvent','YouTube Video',pause_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(), elapsed_seconds,true]);
yt_player_pause = true;
}
}
//fast forward and rewind only work when the user pauses the video and then jumps ahead. it doesn't work if this user just skips into the video since the pause state is always before the play state, the time that the play state takes place, would always be greater
if( previous_state != pause_state && ( yt_player_fast_forward === false || yt_player_rewind === false) ){
//grab the time that the video was paused
current_state_pause = ytplayer.getCurrentTime();
}
//make the previous state pause since this allows us to determine if paused was sent multiple times in a row
previous_state = curr_yt_player_state;
}
else if( curr_yt_player_state === end_state && yt_player_ended === false ){
_gaq.push(['_trackEvent','YouTube Video',end_state , location.protocol + '//' + location.host + location.pathname + '?' + ytplayer.getVideoUrl(),0,true]);
yt_player_ended = true;
//set the replay_video variable to "ended" so we can track if the video was replayed
replay_video = end_state;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment