Advertisement
pijushsaha

Track Vimeo Player with Google Tag Manager

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