After a few hours head scratching I was finally able to make sense of the lunametrics code which essentially looks for embedded YouTube video(s) on your page and triggers event tracking on Google Analytics for:

  • Unstarted
  • Play
  • Watch to End
  • Pause
  • Buffering
  • Cueing

1. Insert the following code into page inside the body tags:

<script src="//cdn.jsdelivr.net/youtube-google-analytics/8.0.2/lunametrics-youtube.gtm.min.js"></script>

*Page obviously must have Google Analytics tracking code within the <head> tags

HTML page e.g.:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXX-XX', 'auto');
ga('send', 'pageview');

</script>
</head>

<body>

<script src="//cdn.jsdelivr.net/youtube-google-analytics/8.0.2/lunametrics-youtube.gtm.min.js"></script>
<iframe width="560" height="315" src="http://www.youtube.com/embed/wavqs3yMN58" frameborder="0" allowfullscreen></iframe>
</body>
</html>

2. You can download Lunametrics script from here http://github.com/lunametrics/youtube-google-analytics/blob/master/lunametrics-youtube.gtm.js and place anywhere within the website directory if you wish to host the script.

*If not in the same location as the web page change the script src in step one to match script location. e.g. <script src=”/path/to/lunametrics-youtube-v7.gtm.js”>

3. Open page and Play, Pause etc. video. Now take a look at Real Time within Google Analytics. You should see something similar to:

YouTube_Track_Events

 

Credit goes to Lunametrics.com – http://www.lunametrics.com/blog/2012/10/22/automatically-track-youtube-videos-events-google-analytics/

Written by Matt Cooper
Hi, I'm Matt Cooper. I started this blog to pretty much act as a brain dump area for things I learn from day to day. You can contact me at: matt@linuxtutorial.co.uk.