Advertisement
Guest User

Cardinal Path - Vimeo Video Tracking Script

a guest
Nov 2nd, 2016
3,680
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <!--
  2. Google Analytics Tag Manager (V2) custom HTML tag for Vimeo video tracking
  3.  
  4. Copyright 2016, Cardinal Path, Inc.
  5.  
  6. Original author: Bill Tripple <btripple@cardinalpath.com>
  7. Revised by: Bogdan Bistriceanu <bbistriceanu@cardinalpath.com>
  8.  
  9. Version 2.0
  10. -->
  11.  
  12. <script>
  13. var dataLayer = (typeof(dataLayer) !== "undefined" && dataLayer instanceof Array) ? dataLayer : [];
  14. var videoLabels=[];
  15. var lastP=[];
  16.  
  17. //we declare variables that will hold information about the video being played
  18. var _playerTitle = {}, _playerAuthor = {}, _playerAuthorURL = {}, _playerUploadDate = {};
  19.  
  20. try{
  21.     init();
  22. }
  23. catch(err){
  24.     dataLayer.push({
  25.         'event': 'gtm.error',
  26.         'errorMessage': e.message,
  27.         'tag': 'CP - UA - Vimeo Video Listener'
  28.     })
  29. }
  30. function init(){
  31.     try{
  32.         var player=document.getElementsByTagName("iframe");
  33.         for (i = 0; i < player.length; ++i) {
  34.             var url=player[i].getAttribute("src");
  35.  
  36.             if(/player\.vimeo\.com\/video/.test(url)){ // vimeo iframe found
  37.                 if(!player[i].hasAttribute("id")){ // id attribute missing
  38.                     player[i].setAttribute("id","vimeo_id_"+i); // add id attribute
  39.                 }
  40.                 var urlUpdated=false;
  41.                 if(!/api=/.test(url)){ // check to see if api parameter is in src attribute
  42.                     url=updateUrl(url,"api",1);
  43.                     urlUpdated=true;
  44.                 }
  45.  
  46.                 if(!/player_id=/.test(url)){ // check if player_id is in src attribute
  47.                     url=updateUrl(url,"player_id",player[i].getAttribute("id"));
  48.                     urlUpdated=true;
  49.                 }
  50.                 if(urlUpdated){ // repopulate src attribute with added parameters
  51.                     player[i].setAttribute("src",url)
  52.                 }
  53.                 videoLabels[player[i].getAttribute("id")]=player[i].getAttribute("src"); // id to label dictionary
  54.             }
  55.         }
  56.  
  57.         // Listen for messages from the player
  58.         if (window.addEventListener){
  59.             window.addEventListener('message', onMessageReceived, false);
  60.         }
  61.         else {
  62.             window.attachEvent('onmessage', onMessageReceived, false);
  63.         }
  64.     }
  65.     catch(err){
  66.     }
  67. }
  68.  
  69. function updateUrl(url,param,value){
  70.     try{
  71.         return url+((/\?/.test(url)) ? "&" : "?")+param+"="+value;  
  72.     }
  73.     catch(err){
  74.     }
  75. }
  76.  
  77. // Handle messages received from the player
  78. function onMessageReceived(e) {
  79.     try{
  80.         var data = e.data;
  81.        
  82.         if(typeof data === "string"){
  83.             data = JSON.parse(data);
  84.         }
  85.        
  86.         switch (data.event) {
  87.             case 'ready':
  88.                 onReady(data);
  89.                 break;
  90.             case 'play':
  91.                 onPlay(data);
  92.                 break;
  93.             case 'pause':
  94.                 onPause(data);
  95.                 break;
  96.             case 'playProgress':
  97.                 onPlayProgress(data);
  98.                 break;
  99.         }
  100.     }
  101.     catch(err){
  102.     }
  103. }
  104.  
  105. // Helper function for sending a message to the player
  106. function post(action, value) {
  107.     try{
  108.         var data = {
  109.           method: action
  110.         };
  111.  
  112.         if (value) {
  113.             data.value = value;
  114.         }
  115.  
  116.         var message = JSON.stringify(data);
  117.         var player = document.getElementsByTagName("iframe");
  118.         var url;
  119.         var prot;
  120.  
  121.  
  122.         for (i = 0; i < player.length; ++i) {
  123.         url=player[i].getAttribute("src");
  124.  
  125.             if(/player\.vimeo\.com\/video/.test(url)){
  126.                 // Check if protocol exists
  127.                 prot = player[i].getAttribute('src').split('?')[0].split('//')[0];
  128.  
  129.                 // If protocol doesn't exist, then need to append to "url"
  130.                 if (!prot){
  131.                     url="https:" + player[i].getAttribute("src").split('?')[0];
  132.                 }
  133.             player[i].contentWindow.postMessage(data, url);
  134.             }
  135.         }
  136.     }
  137.     catch(err){
  138.     }
  139. }
  140.  
  141. function getLabel(id){
  142.     try{
  143.         return videoLabels[id].split('?')[0].split('/').pop();
  144.     }
  145.     catch(err){
  146.     }
  147. }
  148.  
  149. //our function that will use the Vimeo oEmbed API to retrieve additional information about the video
  150. function getVimeoInfo(url, callback) {
  151.            
  152.     var script = document.createElement('script');
  153.         script.type = 'text/javascript';
  154.         script.src = url;
  155.                
  156.         document.getElementsByTagName('body')[0].appendChild(script);
  157. }
  158.  
  159. //the callback function which takes the data received from the Vimeo oEmbed API and places it into the corresponding objectes
  160. function vimeoCallback(e){
  161.     //console.log(e);
  162.     _playerTitle[e['video_id']] = e['title'];
  163.     _playerAuthor[e['video_id']] = e['author_name']
  164.     _playerAuthorURL[e['video_id']] = e['author_url']
  165.     _playerUploadDate[e['video_id']] = e['upload_date']
  166. }
  167.  
  168. function onReady(data) {
  169.     try{
  170.         //execute our function which queries the Vimeo oEmbed API once the embedded videos are "ready"
  171.         getVimeoInfo("https://www.vimeo.com/api/oembed.json?url=https://vimeo.com/"+getLabel(data.player_id)+"&callback=vimeoCallback", vimeoCallback);
  172.  
  173.         post('addEventListener', 'play');
  174.         post('addEventListener', 'pause');
  175.         post('addEventListener', 'finish');
  176.         post('addEventListener', 'playProgress');
  177.     }
  178.     catch(err){
  179.     }
  180. }
  181.  
  182. function onPlay(data){
  183.     try{
  184.         dataLayer.push({
  185.             event: "vimeo",
  186.             eventCategory: "vimeo",
  187.             eventAction: "vimeo play",
  188.             eventLabel: _playerTitle[getLabel(data.player_id)].toLowerCase() + " - " + getLabel(data.player_id),
  189.             vimeo_playerID: getLabel(data.player_id),
  190.             vimeo_playerTitle: _playerTitle[getLabel(data.player_id)].toLowerCase(),
  191.             vimeo_playerAuthor: _playerAuthor[getLabel(data.player_id)].toLowerCase(),
  192.             vimeo_playerAuthorURL: _playerAuthorURL[getLabel(data.player_id)].toLowerCase(),
  193.             vimeo_playerUploadDate: _playerUploadDate[getLabel(data.player_id)],
  194.             nonInteractive: true
  195.         });
  196.     }
  197.     catch(err){
  198.     }
  199. }
  200.  
  201. function onPause(data){
  202.     try{
  203.         dataLayer.push({
  204.             event: "vimeo",
  205.             eventCategory: "vimeo",
  206.             eventAction: "vimeo video pause",
  207.             eventLabel: _playerTitle[getLabel(data.player_id)].toLowerCase() + " - " + getLabel(data.player_id),
  208.             vimeo_playerID: getLabel(data.player_id),
  209.             vimeo_playerTitle: _playerTitle[getLabel(data.player_id)].toLowerCase(),
  210.             vimeo_playerAuthor: _playerAuthor[getLabel(data.player_id)].toLowerCase(),
  211.             vimeo_playerAuthorURL: _playerAuthorURL[getLabel(data.player_id)].toLowerCase(),
  212.             vimeo_playerUploadDate: _playerUploadDate[getLabel(data.player_id)],
  213.             nonInteractive: true
  214.         });
  215.     }
  216.     catch(err){
  217.     }
  218. }
  219.  
  220. // Track progress: 25%, 50%, 75%, 100%
  221. function onPlayProgress(data) {
  222.     try{
  223.         var t = data.data.duration - data.data.seconds <= 1.5 ? 1 : (Math.floor(data.data.seconds / data.data.duration * 4) / 4).toFixed(2);
  224.         if (!lastP[data.player_id] || t > lastP[data.player_id]) {
  225.             lastP[data.player_id]=t;
  226.             if (parseFloat(t) != 0){
  227.                 dataLayer.push({
  228.                     event: "vimeo",
  229.                     eventCategory: "vimeo",
  230.                     eventAction: "vimeo video " +t*100+ "% Complete",
  231.                     eventLabel: _playerTitle[getLabel(data.player_id)].toLowerCase() + " - " + getLabel(data.player_id),
  232.                     vimeo_playerID: getLabel(data.player_id),
  233.                     vimeo_playerTitle: _playerTitle[getLabel(data.player_id)].toLowerCase(),
  234.                     vimeo_playerAuthor: _playerAuthor[getLabel(data.player_id)].toLowerCase(),
  235.                     vimeo_playerAuthorURL: _playerAuthorURL[getLabel(data.player_id)].toLowerCase(),
  236.                     vimeo_playerUploadDate: _playerUploadDate[getLabel(data.player_id)],
  237.                     nonInteractive: true
  238.                 })
  239.             }
  240.         }
  241.     }
  242.     catch(err){
  243.     }
  244. }
  245. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement