Quantcast
Channel: Google Analytics Tip of the Day
Viewing all articles
Browse latest Browse all 105

To Track Embedded YouTube, Don’t Use the Default Embed

$
0
0

If you’ve embedded a YouTube video on a page of your website, it’s important to generate play and complete events within Google Analytics so you can know how many people are viewing the video, how many are making it to the end, and how these actions are influencing other behaviors such as goal completions and Ecommerce.

To capture YouTube events, you can use the YouTube Player API (instead of the default embed) as in the following code:


     <div id="player"></div>
     <script>
         var tag = document.createElement('script');
         tag.src = "http://www.youtube.com/player_api";
         var firstScriptTag = document.getElementsByTagName('script')[0];
         firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

         var player;
         var lastAction = '';
         function onYouTubePlayerAPIReady() {
             player = new YT.Player('player', {
                 playerVars: {
                     modestbranding: true,
                     theme: 'light',
                     rel: 0
                 },
                 height: '360',
                 width: '480',
                 videoId: '4GhUtN4Mlr0',
                 events: {
                     'onStateChange': onPlayerStateChange
                 }
             });
         }
 		
		function onPlayerStateChange(event) {
             switch (event.data) {
                 case YT.PlayerState.PLAYING:
                     //_gaq.push(['_trackEvent', 'video', 'started', player.getVideoUrl()]);
                     _gaq.push(['_trackEvent', 'video', 'started', 'overview']);
                     break;
                 case YT.PlayerState.ENDED:
                     _gaq.push(['_trackEvent', 'video', 'completed', 'overview']);
                     break;
                 case YT.PlayerState.PAUSED:
                     if (lastAction != 'paused') {
                         _gaq.push(['_trackEvent', 'video', 'paused', 'overview']);
                     } else {
                         lastAction = 'paused';
                     }
                     break;
             }
         }
	</script>

Note that when using the YouTube Player API, you can still take advantage of customized settings by specifying PlayerVars as above. (Importantly, the rel=0 prevents related videos from appearing after your own has completed.)

In a previous post, we also dicussed Google Analytics event for embedded Wistia video.

Please share this post:
Facebook Twitter Plusone Linkedin Email

Viewing all articles
Browse latest Browse all 105

Trending Articles