www.flickr.com

Tuesday, November 03, 2009

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=0x006699&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=0x006699&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.

4 Comments:

Blogger Shailendra Dubey said...

did you test this, is this working.

1:32 PM  
Blogger Clancy said...

Yup, this is working for me and tracking data.

1:43 PM  
Blogger Elliot said...

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.

8:52 AM  
Blogger Mike said...

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.

12:01 AM  

Post a Comment

Links to this post:

Create a Link

<< Home