Tracking YouTube Embedded Player Plays with Google Analytics

Ran into this problem while working on a project at work. Couldn’t find this answer anywhere, so I thought I would post it.


Add the YouTube embedded player code to your page as usual, but add the highlighted parameters:

<object width=”425″ height=”344″>
<param name=”movie” value=”http://www.youtube.com/v/ZAOx_HuV3TU&hl=en
&fs=1&color1=0×006699&color2=0x54abd61″></param>
<param name=”allowFullScreen” value=”true”></param>
<param name=”allowscriptaccess” value=”always”></param>
<embed src=”http://www.youtube.com/v/ZAOx_HuV3TU&hl=en
&fs=1&color1=0×006699&color2=0x54abd6&enablejsapi=1
type=”application/x-shockwave-flash” allowscriptaccess=”always”
allowfullscreen=”true” width=”425″ height=”344″ id=’ytvideo’></embed>
</object>

Make sure that the regular tracking code is loaded at the bottom of the page.
Add the following javascript to the top of your page:

<script>
var playedOnce = false;

function onYouTubePlayerReady(playerid) {
player = document.getElementById(‘ytvideo’);
player.addEventListener(‘onStateChange’, ‘youtubeEvent’);
}

function youtubeEvent(state) {
if (state == 1) {
if (!playedOnce) {
playedOnce = true;
pageTracker._trackEvent(‘video’, ‘unique_play_per_page’);
}
pageTracker._trackEvent(‘video’, ‘play’);
return;
}
if (state == 0) {
pageTracker._trackEvent(‘video’, ‘ended’);
return;
}
}
</script>

This will generate three types of page events:
1. ‘play’ is an event everytime the player starts playing. A play event is also when someone pauses and starts playing or scrolls to a different part of the video. This is why counting number of ‘plays’ can be misleading.
2. ‘unique_play_per_page’ counts ‘play’ events, but only one per page load.
3. ‘ended’ counts videos that have been played to the end.

8 thoughts on “Tracking YouTube Embedded Player Plays with Google Analytics

  1. I am unable to get it working on a WordPress site. I copied all the code, incl. the YouTube code as is. Did anyone get it working on WordPress? My test site is elliotsvan.com.
    Any help would be appreciated.

  2. We have the code working, but it does not track anyone using IE because the variables aren't in the "object" tag, only the "embed"

    Has anyone found a way to get IE views to track in GA? I tried adding the same variables to the "object" code, but I just get java errors.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>