Google Tag Manager 上對Vimeo影片做追蹤(GA4)

Google Analytics Haran 2年前 (2023-02-08) 1027次瀏覽 2條留言

發佈時間:2023年02月08日
更新時間:2024年09月05日

這一篇介紹如何在GTM上對Vimeo影片做追蹤蹤,如要對Youtube影片做追蹤,延伸閱讀:【GA4設定】Google Analytics 4 中對Youtube影片做追蹤

假設我現在要追蹤 https://grounded.world/our-work-hidden-camera-on-hunger/上的Vimeo影片播放:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

實現方式

通過GTM裡注入一段JavaScript去監聽Vimeo影片的播放,然後在通過dataLayer.push發送事件,如JavaScript如下:

<!--
Google Analytics Tag Manager (V2) custom HTML tag for Vimeo video tracking

Copyright 2016, Cardinal Path, Inc.

Original author: Bill Tripple <btripple@cardinalpath.com>
Revised by: Bogdan Bistriceanu <bbistriceanu@cardinalpath.com>
Updated by: Julius Fedorovicius <julius@analyticsmania.com> and Richard Outram <Richard.Outram@simmbiotic.com>

Version 2.1
-->

<script>
var dataLayer = (typeof(dataLayer) !== "undefined" && dataLayer instanceof Array) ? dataLayer : [];
var videoLabels=[];
var lastP=[];


//we declare variables that will hold information about the video being played
var _playerTitle = {}, _playerAuthor = {}, _playerAuthorURL = {}, _playerUploadDate = {}; 

try{
 init();
}
catch(err){
 dataLayer.push({
 'event': 'gtm.error',
 'errorMessage': e.message,
 'tag': 'CP - UA - Vimeo Video Listener'
 })
}
function init(){
 try{
 var player=document.getElementsByTagName("iframe");
 for (i = 0; i < player.length; ++i) {
 var url=player[i].getAttribute("src");

 if(/player\.vimeo\.com\/video/.test(url)){ // vimeo iframe found
 if(!player[i].hasAttribute("id")){ // id attribute missing
 player[i].setAttribute("id","vimeo_id_"+i); // add id attribute
 }
 var urlUpdated=false;
 if(!/api=/.test(url)){ // check to see if api parameter is in src attribute
 url=updateUrl(url,"api",1);
 urlUpdated=true;
 }

 if(!/player_id=/.test(url)){ // check if player_id is in src attribute
 url=updateUrl(url,"player_id",player[i].getAttribute("id"));
 urlUpdated=true;
 }
 if(urlUpdated){ // repopulate src attribute with added parameters
 player[i].setAttribute("src",url)
 }
 videoLabels[player[i].getAttribute("id")]=player[i].getAttribute("src"); // id to label dictionary
 }
 }

 // Listen for messages from the player
 if (window.addEventListener){
 window.addEventListener('message', onMessageReceived, false);
 }
 else {
 window.attachEvent('onmessage', onMessageReceived, false);
 }
 }
 catch(err){
 }
}

function updateUrl(url,param,value){
 try{
 return url+((/\?/.test(url)) ? "&" : "?")+param+"="+value; 
 }
 catch(err){
 }
}

// Handle messages received from the player
function onMessageReceived(e) {
 try{
 var data = e.data;
 
 if(typeof data === "string"){
 data = JSON.parse(data);
 }
 
 switch (data.event) {
 case 'ready':
 onReady(data);
 break;
 case 'play':
 onPlay(data);
 break;
 case 'pause':
 onPause(data);
 break;
 case 'timeupdate':
 onPlayProgress(data);
 break;
 }
 }
 catch(err){
 }
}

// Helper function for sending a message to the player
function post(action, value) {
 try{
 var data = {
 method: action
 };

 if (value) {
 data.value = value;
 }

 var message = JSON.stringify(data);
 var player = document.getElementsByTagName("iframe");
 var url;
 var prot;


 for (i = 0; i < player.length; ++i) {
 url=player[i].getAttribute("src");

 if(/player\.vimeo\.com\/video/.test(url)){
 // Check if protocol exists
 prot = player[i].getAttribute('src').split('?')[0].split('//')[0];

 // If protocol doesn't exist, then need to append to "url"
 if (!prot){
 url="https:" + player[i].getAttribute("src").split('?')[0];
 }
 player[i].contentWindow.postMessage(data, url);
 }
 }
 }
 catch(err){
 }
}

function getLabel(id){
 try{
 return videoLabels[id].split('?')[0].split('/').pop();
 }
 catch(err){
 }
}

//our function that will use the Vimeo oEmbed API to retrieve additional information about the video
function getVimeoInfo(url, callback) {
 
 var script = document.createElement('script');
 script.type = 'text/javascript';
 script.src = url;
 
 document.getElementsByTagName('body')[0].appendChild(script);
}

//the callback function which takes the data received from the Vimeo oEmbed API and places it into the corresponding objectes
function vimeoCallback(e){
 //console.log(e);
 _playerTitle[e['video_id']] = e['title'];
 _playerAuthor[e['video_id']] = e['author_name']
 _playerAuthorURL[e['video_id']] = e['author_url']
 _playerUploadDate[e['video_id']] = e['upload_date']
}

function onReady(data) {
 try{
 //execute our function which queries the Vimeo oEmbed API once the embedded videos are "ready"
 getVimeoInfo("https://www.vimeo.com/api/oembed.json?url=https://vimeo.com/"+getLabel(data.player_id)+"&callback=vimeoCallback", vimeoCallback);

 post('addEventListener', 'playProgress');
 }
 catch(err){
 }
}




// Track progress: 25%, 50%, 75%, 100%
function onPlayProgress(data) {
 try{
 var t = data.data.duration - data.data.seconds <= 1.5 ? 1 : (Math.floor(data.data.seconds / data.data.duration * 20) / 20).toFixed(2); if (!lastP[data.player_id] || t > lastP[data.player_id]) {
 lastP[data.player_id]=t;
 if (parseFloat(t) != 0 && (t==0.15 || t==0.5 || t===0.9)){
 dataLayer.push({
 event: "video",
 video_percentage: t*100+ "% Complete",
 video_name: _playerTitle[getLabel(data.player_id)].toLowerCase() + " - " + getLabel(data.player_id),
 vimeo_playerID: getLabel(data.player_id),
 vimeo_playerTitle: _playerTitle[getLabel(data.player_id)].toLowerCase(),
 vimeo_playerAuthor: _playerAuthor[getLabel(data.player_id)].toLowerCase(),
 vimeo_playerAuthorURL: _playerAuthorURL[getLabel(data.player_id)].toLowerCase(),
 vimeo_playerUploadDate: _playerUploadDate[getLabel(data.player_id)],
 nonInteractive: true
 })
 }
 }
 }
 catch(err){
 }
}
</script>

 

設定過程

添加Vimeo影片監聽代碼

GTM中點擊「變數」——「新增」——「請選擇變數類型以開始設定…」——「自訂 JavaScript」,命名為 “Custom Javascript – Is Vimeo Present”, 然後做如下設定:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

這個變數是用於判斷Vimeo是否已經加載好。

 

使用到的代碼:

//this function checks for the presence of an embedded Vimeo video
//if one or more videos are present, return true, otherwise return false

function () {
  for (var e = document.getElementsByTagName("iframe"), x=0; x < e.length; x++) {
    if (/^https?:\/\/player.vimeo.com/.test(e[x].src)) {
      return true;
    }
  }
  return false;
}

 

 

GTM中點擊「觸發條件」—「新增」—「選擇一個觸發條件類型以開始設定」——「網頁瀏覽 – 視窗已載入」,命名為“Pageview – Vimeo Player Is Present”,然後做如下設定:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

 

 

GTM中點擊「代碼」—「新增」—「請選擇代碼類型以開始設定…」——「自訂HTML」,命名為“cHTML – Vimeo Listener”,然後做如下設定:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

這裡的程式就是實現方式裡的JavaScript。

設定事件

從JavaScript裡,可以知道變數是video_name、video_percentage

GTM中點擊「變數」——「新增」——「請選擇變數類型以開始設定…」——「資料層變數」,命名為 “Video Name”, 然後做如下設定:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

同理設定Video Percentage。

 

從JavaScript裡,可以知道event是video。

在GTM中點擊「觸發條件」—「新增」—「選擇一個觸發條件類型以開始設定」——「自訂事件」,命名為“Custom – Video Interaction”,然後做如下設定:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

 

 

最後就是設定代碼。

在GTM中點擊「代碼」—「新增」—「請選擇代碼類型以開始設定…」——「Google Analytics(分析):GA4 事件」,命名為“Event—Video Tracking”,做如下設定:

Google Tag Manager 上對Vimeo影片做追蹤(GA4)

 

接下來就是預覽調試,你可以用以下任意方法:

 

 

最後還需要將事件參數在GA4的自訂定義裡註冊。

 


如果您在操作上仍有任何疑問,歡迎留言交流,或加入:Google Analytics 4交流社團發問
Like (0)
發佈我的留言
取消留言
表情 贴图 加粗 删除线 居中 斜体

Hi,*为發佈留言必須填寫。

  • 顯示名稱*
  • 電子郵件地址*
  • 個人網站網址
(2)个小伙伴在留言
  1. 你的網站我受益良多 請問我設定完但是到最後一直無法觸發video的自訂事件,有可能是什麼原因呢?
    michelle2023-12-28 23:53 回覆 Mac OS X | Chrome 119.0.0.0
    • 這種方式僅適用於Vimeo的視頻追蹤。 GTM裡預覽調試,然後看Summary裡:如果有看到video的事件,但沒Tag沒觸發,那就是觸發條件設定有問題;如果看不到video的相關設定,可能是Vimeo視頻監聽代碼或一些自訂HTML的程式有問題。
      Haran2024-01-01 22:22 回覆 Mac OS X | Chrome 120.0.0.0