How to Track YouTube Player Events in Google Analytics

Blog - How to Track YouTube Player Events In Google Analytics

Anyone who has embedded YouTube videos on their website knows how valuable it can be to find out whether visitors are actually watching those videos. You might want to track whether people are watching until the end or whether they stop short. Here’s how to find that out using the YouTube API and some Google Analytics ninja skills.

The original example for this came from Brian Clifton’s newly published Advanced Web Metrics with Google Analytics, which we’ve been reading here at BFM. We realized that there were a few small omissions in the jscript provided on page 250 (in 2012 edition) so we have corrected those below.


Track when a visitor clicks to play a video and whether they watch it until the end. You’ll be able to see this in your Google Analytics reports in your Events section:

track youtube events in google analytics


1. Place your usual Google Analytics tracking code (asynchronous) in your header.

2. Create an empty div element within the body, with an id of “player”. This is where your YouTube video will be placed shortly.

<div id="player"</div

3. Make a script tag, and insert the YouTube iframe player API code. Don’t close the script tag, there’s still more to do.

var tag = document.createElement('script'); 
tag.src = ""; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

4. Create the iframe and player. Replace the ‘zLQFkztsozw’ with your video ID tag and customize your video height and width requirements.

var player; 
function onYouTubePlayerAPIReady() { 
player = new YT.Player('player', { 
height: '390', 
width: '640', 
videoId: 'zLQFkztsozw', 
events: { 
'onReady': onPlayerReady, 
'onStateChange': onPlayerStateChange 
function onPlayerReady(event) { 

5. Use the onPlayerStateChange method to look for events, such as the video starting or stopping. You can also close the script tag here.

function onPlayerStateChange(event) { 
if ( ==YT.PlayerState.PLAYING) 
{_gaq.push(['_trackEvent', 'Videos', 'Play', 
player.getVideoUrl() ]); } 
if ( ==YT.PlayerState.ENDED) 
{_gaq.push(['_trackEvent', 'Videos', 'Watch to End', 
player.getVideoUrl() ]); } } 

I hope that this helps you get a better insight into how users are interacting with your web video production embedded on your website. If you have any questions, please comment below!