用 Google Tag Manager 對H5視頻做追蹤(GA4)

Google Analytics Haran 1年前 (2023-02-21) 850次瀏覽 0條留言

這一篇介紹如何在GTM上對H5視頻做追蹤蹤,其實H5視頻的追蹤和Vimeo的是一樣的,延伸閱讀:Google Tag Manager上對Vimeo視頻做追蹤(GA4)

 

實現方式

通過GTM裡注入一段JavaScript去監聽H5視頻的加載,然後在通過dataLayer.push發送事件,如JavaScript如下:

<script>
// Let's wrap everything inside a function so variables are not defined as globals 
(function() {
    // This is gonna our percent buckets ( 25%-75% ) 
    var divisor = 25;
    // We're going to save our players status on this object. 
    var videos_status = {};
    // This is the funcion that is gonna handle the event sent by the player listeners 
    function eventHandler(e) {
        switch (e.type) {
            // This event type is sent everytime the player updated it's current time, 
            // We're using for the % of the video played. 
        case 'timeupdate':
            // Let's set the save the current player's video time in our status object 
            videos_status[e.target.id].current = Math.round(e.target.currentTime);
            // We just want to send the percent events once 
            var pct = Math.floor(100 * videos_status[e.target.id].current / e.target.duration);
            for (var j in videos_status[e.target.id]._progress_markers) {
                if (pct >= j && j > videos_status[e.target.id].greatest_marker) {
                    videos_status[e.target.id].greatest_marker = j;
                }
            }
            // current bucket hasn't been already sent to GA?, let's push it to <a href="https://www.haranhuang.com/tag/gtm" title="查看更多关于GTM的文章" target="_blank">GTM</a>
            if (videos_status[e.target.id].greatest_marker && !videos_status[e.target.id]._progress_markers[videos_status[e.target.id].greatest_marker]) {
                videos_status[e.target.id]._progress_markers[videos_status[e.target.id].greatest_marker] = true;
                dataLayer.push({
                    'event': 'video',
                    'video_status': 'progress',
                    'video_provider' : 'generic html5 video player',
                    'video_percent': videos_status[e.target.id].greatest_marker,
                    // We are sanitizing the current video src string, and getting just the video name part
                    'video_title': decodeURIComponent(e.target.currentSrc.split('/')[e.target.currentSrc.split('/').length - 1])
                });
            }
            break;
            // This event is fired when user's click on the play button
        case 'play':
            dataLayer.push({
                'event': 'video',
                'video_status' : 'play',
                'video_provider' : 'generic html5 video player',
                'video_percent': videos_status[e.target.id].greatest_marker,
                'video_title': decodeURIComponent(e.target.currentSrc.split('/')[e.target.currentSrc.split('/').length - 1])
            });
            break;
            // This event is fied when user's click on the pause button
        case 'pause':
            if (videos_status[e.target.id].greatest_marker < '75') {
            dataLayer.push({
                'event': 'video',
                'video_status' : 'pause',
                'video_provider' : 'generic html5 video player',
                'video_percent': videos_status[e.target.id].greatest_marker,
                'video_title': decodeURIComponent(e.target.currentSrc.split('/')[e.target.currentSrc.split('/').length - 1])
            });
            }
            break;
            // If the user ends playing the video, an Finish video will be pushed ( This equals to % played = 100 )  
        case 'ended':
            dataLayer.push({
                'event': 'video',
                'video_status' : 'complete',
                'video_provider' : 'generic html5 video player',
                'video_percent': '100',
                'video_title': decodeURIComponent(e.target.currentSrc.split('/')[e.target.currentSrc.split('/').length - 1])
            });
            break;
        default:
            break;
        }
    }
    // We need to configure the listeners
    // Let's grab all the the "video" objects on the current page     
    var videos = document.getElementsByTagName('video');
    for (var i = 0; i < videos.length; i++) {
        // In order to have some id to reference in our status object, we are adding an id to the video objects
        // that don't have an id attribute. 
        var videoTagId;
        if (!videos[i].getAttribute('id')) {
            // Generate a random alphanumeric string to use is as the id
            videoTagId = 'html5_video_' + Math.random().toString(36).slice(2);
            videos[i].setAttribute('id', videoTagId);
        }// Current video has alredy a id attribute, then let's use it <img draggable="false" class="emoji" alt="?" src="https://s.w.org/images/core/emoji/2/svg/1f642.svg">
        else {
            videoTagId = videos[i].getAttribute('id');
        }
        // Video Status Object declaration  
        videos_status[videoTagId] = {};
        // We'll save the highest percent mark played by the user in the current video.
        videos_status[videoTagId].greatest_marker = 0;
        // Let's set the progress markers, so we can know afterwards which ones have been already sent.
        videos_status[videoTagId]._progress_markers = {};
        for (j = 0; j < 100; j++) {
            videos_status[videoTagId].progress_point = divisor * Math.floor(j / divisor);
            videos_status[videoTagId]._progress_markers[videos_status[videoTagId].progress_point] = false;
        }
        // On page DOM, all players currentTime is 0 
        videos_status[videoTagId].current = 0;
        // Now we're setting the event listeners. 
        videos[i].addEventListener("play", eventHandler, false);
        videos[i].addEventListener("pause", eventHandler, false);
        videos[i].addEventListener("ended", eventHandler, false);
        videos[i].addEventListener("timeupdate", eventHandler, false);
        videos[i].addEventListener("ended", eventHandler, false);
    }
})();
</script>

 

設定過程

添加H5視頻監聽代碼

GTM中點擊「變數」——「新增」——「請選擇變數類型以開始設定…」——「自訂 JavaScript」,命名為 “cjs – is HTML5 Video on a page”, 然後做如下設定:

用 Google Tag Manager 對H5視頻做追蹤(GA4)

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

 

使用到的代碼:

function () {
var video = document.getElementsByTagName('video').length;
if (video > 0) {
return true;
}
else {
return false;
}
}

 

 

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

用 Google Tag Manager 對H5視頻做追蹤(GA4)

 

 

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

用 Google Tag Manager 對H5視頻做追蹤(GA4)

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

設定事件

從JavaScript裡,可以知道變數是video_status、video_percent和video_provider

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

用 Google Tag Manager 對H5視頻做追蹤(GA4)

同理設定video_percent和video_provider

 

 

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

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

用 Google Tag Manager 對H5視頻做追蹤(GA4)

 

 

最後就是設定代碼。

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

用 Google Tag Manager 對H5視頻做追蹤(GA4)

 

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

 

 

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

 

 

Referral:

 


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

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

  • 顯示名稱*
  • 電子郵件地址*
  • 個人網站網址