public
Last active

Track YouTube Events in Google Analytics

  • Download Gist
ga-youtube.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
//NOTE: you must also include https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api?enablejsapi=1&version=3&showinfo=0";
 
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
 
var player;
 
function onYouTubePlayerAPIReady() {
player = new YT.Player('target_div_id', { //replace target_div_id with the id of the div the video should render in
height: '480',
width: '640',
videoId: 'XXXXX', //REPLACE THIS WITH YOUR VIDEO ID
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
 
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
_gaq.push(['_trackEvent', 'Videos', 'Play', player.getVideoUrl() ]);
}
if (event.data == YT.PlayerState.ENDED) {
_gaq.push(['_trackEvent', 'Videos', 'Completed', player.getVideoUrl() ]);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.