YouTube Video Event Tracking

Easily Track YouTube Videos with Google Analytics has Javascript code available to perform tracking on YouTube video events in Google Analytics. I encountered a problem where the code didn’t work with YouTube videos already embedded with iframes. The YouTube JavaScript Player API Reference says that it should be able to handle YouTube videos embedded in iframes tags. I found a work-around by replacing iframes tags with div tags and creating a player for each div created. The following code requires jQuery and was tested with version 1.7.2.


function trackYouTube() {
var i = 1;
$('iframe').each(function() {
var vidSrc = "";
var newDivID = "";
var vidID = "";

if ($(this).attr('src')===undefined) {
} else {
vidSrc = $(this).attr('src');
}

var regex = /h?t?t?p?s?\:?\/\/www\.youtube\.com\/embed\/([\w-]{11})(?:\?.*)?/;
var matches = vidSrc.match(regex);
if (matches && matches.length > 1) {
vidID = matches[1]; // Get the id of the youtube video

// Create a new element for each video
newDivID = vidID + '-num' + i;
var div = $('<div/>', { id: newDivID });
divArray[i] = newDivID;

// Replace the iFrame with the div we created
$(this).replaceWith(div);
videoArray[i] = vidID;
i++;
}
});
}

function updateYouTubePlayers() {
for (var key in videoArray) {
var newDivID = divArray[key];
var vidID = videoArray[key];
playerArray[key] = new YT.Player(document.getElementById(newDivID), { videoId: vidID, events: { 'onStateChange': onPlayerStateChange }});
}
}

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var divArray = {};
var videoArray = {};
var playerArray = {};

(function($) {
$(document).ready(function() {
trackYouTube();
});
})(jQuery);

function onYouTubeIframeAPIReady() {
updateYouTubePlayers();
}

var _pauseFlag = false;
function onPlayerStateChange(event) {
var videoID = "";
try {
videoID = event.target.a.id;
} catch (e) { }

if (event.data ==YT.PlayerState.PLAYING){
_gaq.push(['_trackEvent', 'Videos', 'Play', videoID ]);
_pauseFlag = false;
}
if (event.data ==YT.PlayerState.ENDED){
_gaq.push(['_trackEvent', 'Videos', 'Watched to End', videoID ]);
}
if (event.data ==YT.PlayerState.PAUSED && _pauseFlag == false){
_gaq.push(['_trackEvent', 'Videos', 'Pause', videoID ]);
_pauseFlag = true;
}
if (event.data ==YT.PlayerState.BUFFERING){
_gaq.push(['_trackEvent', 'Videos', 'Buffering', videoID ]);
}
if (event.data ==YT.PlayerState.CUED){
_gaq.push(['_trackEvent', 'Videos', 'Cueing', videoID ]);
}
}

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *