This article will help you:
  • Set up and track YouTube videos on your page
  • Set up and track Vimeo videos on your page

Including videos on your website can be a great way to engage users and deliver complex or a large amount of information in an easily digestible way. We love to do this here at Optimizely! Perhaps you want to showcase a new feature on your site or explain where items have moved after a site redesign. You can use Optimizely to track the number of visitors who watch a YouTube or Vimeo video on your website by using a combination of YouTube's Player API, Vimeo’s Player JavaScript API, and Optimizely's Custom Event API.

The YouTube and Vimeo APIs allow you to track three different types of events in Optimizely:

  • The number of times the videos was played
  • The number of times the video was paused
  • The number of times the video was watched until the end

Before you can track those events in Optimizely you will need to make sure the video is added to your page with the right identifiers to ensure that events will be fired. You can either amend the video that is already on your site, or you can add a video as part of an Optimizely experiment using our Insert HTML and Edit HTML features.

YouTube and Vimeo players can be embedded in a web page or an app using an <iframe> tag. Vimeo video tracking requires that a version of jQuery higher than Optimizely’s full version be added to your page.

YouTube <iframe> implementation

Embedding videos using an <iframe> tag is the most common and supported way to add YouTube videos to your website.

A typical YouTube iframe would look like this:

<iframe width="420" height="315" src="https://www.youtube.com/embed/pJnpNgd-UdY" frameborder="0" allowfullscreen></iframe>

To obtain this iFrame code for your video, go to your video page on YouTube, click the Share link below the video, and then click Embed. Copy the <iframe> code.

To enable the tracking of events on that video you need to add some extra parameters to the <iframe> tag:

  • You need to give the <iframe> an id. This id will be used later when pushing events to Optimizely
  • Enable the Javascript API by adding the following string to the URL: ?enablejsapi=1
  • You also need to add the class video-tracking. This class will tell the tracking code which videos should be tracked and which ones should not. If you have more than one video on a page, you might not want to track events on all of them.

After you add these three items to the <iframe> tag, it will look like this:

<iframe id="myVideo" class="video-tracking" width="420" height="315" src="https://www.youtube.com/embed/pJnpNgd-UdY?enablejsapi=1" frameborder="0" allowfullscreen>/iframe>
 
Note:

To track events on an iframe video, the tracking code uses the YouTube iFrame API. This API uses a callback function named onYouTubeIframeAPIReady. For the tracking to work you need to make sure that you are not already implementing that function on your page.

Adding the YouTube tracking code to your page

The next step is to add the tracking code to your page so it fires events when videos are played/paused/finished.

You need to add the following JavaScript code in order to call the YouTube API and bind the custom events to the video player actions.. You may add this code directly to your page, you may add it within Experiment JavaScript in Optimizely, or you may add it to your variation code.

/* _optimizely_evaluate=force */
//this is a boilerplate set of calls to append a new script to your head tag
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "//www.youtube.com/iframe_api";
head.appendChild(script);
/**
* iFrame API (for iframe videos)
* onYouTubeIframeAPIReady is called for each player when it is ready
*/
window.onYouTubeIframeAPIReady = function(){
 
    $('.video-tracking').each(function() {
        var iframe = optimizely.$(this);
        // get the player(s)
        var player = new YT.Player(iframe[0], {
            events: {
                'onReady': function(e){
                    console.log('YouTube player \'' +iframe.attr('id') +'\': ready');
                    e.target._donecheck=true;
                },
                'onStateChange': function(e){
                    onStateChange(iframe.attr('id'), e);
                }
            }
        });
    });
};

//execute the API calls for play, pause, and finish
window.onStateChange = function(playerid, state) {
    if(state.data === 0) { 
        onFinish(playerid);
    } else if(state.data === 1) { 
        onPlay(playerid);
    } else if(state.data === 2) { 
        onPause(playerid);
    }
};

//for each of the above three states, make a custom event API call to Optimizely
window.onPause = function(id) {
    console.log('YouTube player \'' +id +'\': pause');
    window['optimizely'] = window['optimizely'] || [];
    window.optimizely.push(["trackEvent", id +"Pause"]);
};
 
window.onFinish = function(id) {
    console.log('YouTube player \'' +id +'\': finish');
    window['optimizely'] = window['optimizely'] || [];
    window.optimizely.push(["trackEvent", id +"Finish"]);
};
 
window.onPlay = function(id) {
    console.log('YouTube player \'' +id +'\': play');
    window['optimizely'] = window['optimizely'] || [];
    window.optimizely.push(["trackEvent", id +"Play"]);
};
/* _optimizely_evaluate=safe */

Alternatively you can upload the attached file youtube-track-event.js to your website and link to it from your pages. This file can be found at the bottom of the article:

<script src="https://<mydomain>/js/youtube-track-events.js"></script>
 
 
Note:

Make sure to replace the domain name with your domain name and modify the /js path if you copied the files into a different folder.

Vimeo <iframe> implementation

Embedding videos using an <iframe> tag is the most common and supported way to add Vimeo videos to your website.

A typical Vimeo iframe would look like this:

<iframe src="//player.vimeo.com/video/15321875" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>

To obtain this iFrame code for your video, go to your video page on Vimeo, click the airplane icon on the right side of the video screen, and then copy the code in the Embed box.

To enable the tracking of events on that video you need to add some extra parameters to the <iframe> tag:

  • You need to give the <iframe> an id. This id will be used later when pushing events to Optimizely
  • Append this same id to the video URL with the parameter player_id=<id>
  • Enable the Javascript API by adding the following string to the URL: api=1
  • You also need to add the class video-tracking. This class will tell the tracking code which videos should be tracked and which ones should not. If you have more than one video on a page, you might not want to track events on all of them.

After you add these four items to the <iframe> tag, it will look like this:

<iframe id="myVideo" class="video-tracking" width="500" height="281" src="//player.vimeo.com/video/15321875?api=1&player_id=myVideo" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
 
Note:

To track events on an iframe video, the tracking code uses the Vimeo Player API. This API uses a callback function named initPlayer. For the tracking to work you need to make sure that you are not already implementing that function on your page.

Adding the Vimeo tracking code to your page

The next step is to add the tracking code to your page so it fires events when videos are played/paused/finished.

You need to add the following JavaScript code in order to call the Vimeo API and bind the custom events to the video player actions. You may add this code directly to your page, you may add it within Experiment JavaScript in Optimizely, or you may add it to your variation code.

/* _optimizely_evaluate=force */
//this is a boilerplate function to append a new script to your head tag
function loadScript(url, callback) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

//bind the event to the callback function.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

//specify the Vimeo API script
loadScript('http://a.vimeocdn.com/js/froogaloop2.min.js', initPlayer);

//function to initialize the player, establish the three events, and define how those events will be tracked in Optimizely
function initPlayer() {

    window.$('.video-tracking').each(function() {

 		// get the vimeo player(s)
        var iframe = window.$(this);
        var player = window.$f(iframe[0]);

        // When the player is ready, add listeners for pause, finish, and playProgress
        player.addEvent('ready', function() {
       		console.log('Vimeo player \'' +iframe.attr('id') +'\': ready');

//these are the three standard events Vimeo's API offers
            player.addEvent('play', onPlay);
			player.addEvent('pause', onPause);
            player.addEvent('finish', onFinish);
        });
 	});

//define the custom events to push to Optimizely
//appending the id of the specific video (dynamically) is recommended
//to make this script extensible to all possible videos on your site
    function onPause(id) {
        console.log('Vimeo player \'' +id +'\': pause');
        window['optimizely'] = window['optimizely'] || [];
        window.optimizely.push(["trackEvent", id +"Pause"]);
    }

    function onFinish(id) {
        console.log('Vimeo player \'' +id +'\': finish');
        window['optimizely'] = window['optimizely'] || [];
        window.optimizely.push(["trackEvent", id +"Finish"]);
    }

    function onPlay(id) {
        console.log('Vimeo player \'' +id +'\': play');
        window['optimizely'] = window['optimizely'] || [];
        window.optimizely.push(["trackEvent", id +"Play"]);
    }
}
/* _optimizely_evaluate=safe */

Alternatively you can upload the attached file vimeo-track-event.js to your website and link to it from your pages.This file can be found at the bottom of the article:

<script src="http://<mydomain>/js/vimeo-track-events.js"></script>
 
Note:

Make sure to replace the domain name with your domain name and modify the /js path if you copied the files into a different folder.

Configuring Optimizely Custom Event Goals

The tracker for your video player of choice is now in place and it will push data to Optimizely every time a video is played, paused or finished. The last thing to do is to create custom event goals in Optimizely so you can see those conversions on the Results Page.

You should already have an experiment created in Optimizely. In that experiment you can create three custom event goals.

  • The first one is to capture the video 'play' event. The custom event name should be <id>Play, where id is either the iframe id for the iframe implementation or the player id for the object implementation. In our case the id was myVideo so the event will be myVideoPlay. The name of the goal can reflect which video player you are using.

  • The second one is to capture the video 'pause' event. The custom event name should be <id>Pause, where id is either the iframe id for the iframe implementation or the player id for the object implementation. In our case the id was myVideo so the goal will be myVideoPause. The name of the goal can reflect which video player you are using.
 
Note:

The pause event is also called at the end of the video, just before the video finish event.

  • The last one is to capture the video 'finish' event. The custom event name should be <id>Finish, where id is either the iframe id for the iframe implementation or the player id for the object implementation. In our case the id was myVideo so the goal will be myVideoFinish. The name of the goal can reflect which video player you are using.

Now if you start the experiment you will be able to see the play/pause/finish events counted in Optimizely.

 
Note:

Remember that Optimizely events are de-duplicated on the results page so each visitor can only convert a goal once.