Track video views on Youtube and Vimeo

  • Updated
  • Optimizely Web Experimentation

Including videos on your website can be a great way to engage visitors and deliver complex or large amounts of information in a digestible way. For example, you use videos to showcase a feature on your site or explain where to find specific content after a site redesign.

In addition to a hosting platform and an embeddable player element, most video hosting solutions provide APIs for deeper video functionality. You can use the methods these APIs provide with Optimizely Web Experimentation's custom events to send a conversion to the Optimizely Experimentation Results page when a visitor interacts with your video.

This example solution lets you send a conversion event when a visitor:

  • Clicks Play.

  • Pauses the video.

  • Watches more than half of the video.

  • Finishes the video.

Use these code samples as a reference with the help of a developer. They are provided as-is; Optimizely will not troubleshoot or debug these code samples.

How video tracking works

First, determine what video vendor your site uses. Your vendor’s developer documentation will explain which functions are available from their API. Here is where to find the documentation for a few common video hosting providers:

Most of these vendors do not provide access to their APIs by default when a video is embedded. For example, Vimeo requires you to create a player object on the page where you have embedded your video:

/* _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('https://player.vimeo.com/api/player.js', initPlayer);

YouTube requires that you add a query parameter to your embed URL:

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

Your developer must determine how to add API access to your embedded video using Optimizely Web Experimentation or by adding code to your site. 

After your video vendor’s API is added to the page where you have embedded your video, your developers must write a script that:

  • Creates an object that identifies the embedded video player on the page.

  • Defines a set of callback functions that executes when a visitor acts, such as playing, pausing, or completing a video.

  • Includes an Optimizely Web Experimentation custom event that is pushed each time one of the player callback functions is executed.

After verifying and implementing the code, add the necessary video tracking events to your project's implementation settings as custom events.

The code samples in the following section should give your developers an idea of what a real video-tracking implementation looks like. Remember that these code samples are presented as is and are not maintained or supported by Optimizely Web Experimentation.

YouTube code sample (requires jQuery)

This code sample is provided as a reference and is not maintained by Optimizely Experimentation. 

//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 = "https://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 Web Experimentation
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"]);
};

Vimeo code sample

This code sample is provided as a reference and is not maintained by Optimizely Experimentation. 

//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('https://player.vimeo.com/api/player.js', initPlayer);

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

 

        // get the vimeo player(s)
       var iframe = document.querySelector('.video-tracking');
         console.log("iframe value =" + iframe);
           var player = new Vimeo.Player(iframe);
             console.log('%cvideo player created', 'background: #222; color: #bada55;');

//these are the three standard events Vimeo's API offers
           player.on('play', onPlay);
                       player.on('pause', onPause);
           player.on('ended', onEnded);

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

   function onEnded() {
       console.log('Vimeo player: finish');
       window['optimizely'] = window['optimizely'] || [];
       window.optimizely.push(["trackEvent", "vimeoPlayerFinish"]);
   }

   function onPlay(id) {
       console.log('Vimeo player: play');
       window['optimizely'] = window['optimizely'] || [];
       window.optimizely.push(["trackEvent", "vimeoPlayerPlay"]);
   }
}