gpt4 book ai didi

javascript - 如何修复无法正常工作的 HTML5 视频 Javascript 跟踪代码

转载 作者:太空狗 更新时间:2023-10-29 16:34:54 27 4
gpt4 key购买 nike

我有一些我在网上找到的 JavaScript 代码,它为我的 HTML5 视频提供了谷歌分析的统计数据。然而,该代码仅正确 显示“视频已播放”和“视频已暂停”的统计信息,但其余信息不会显示甚至不会计算。其余信息是:

“25% 的视频已观看”,“观看了 50% 的视频”,“观看了 75% 的视频”,“100% 视频已观看”。

如何让下面的代码正常工作?此外,Google Analytics 是跟踪这些统计数据的唯一方法还是有其他方法?

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', init, false)
var videoId = document.getElementById('bigvid3')
var videoTitle = videoId.getAttribute('data-description')
var videoTitle = 'bigvid3'

function init () {
videoId.addEventListener('play', videoPlay, false)
videoId.addEventListener('pause', videoPause, false)
videoId.addEventListener('ended', videoEnd, false)
videoId.addEventListener('timeupdate', videoTimeUpdate, false)

}

function setKeyFrames (duration) {
var quarter = (duration / 4).toFixed(1)
sessionStorage.setItem('one', quarter)
sessionStorage.setItem('two', (quarter * 2).toFixed(1))
sessionStorage.setItem('three', (quarter * 3).toFixed(1))
}

function videoTimeUpdate () {
var curTime = videoId.currentTime.toFixed(1)
switch (curTime) {
case sessionStorage.getItem('one'):
ga('send', 'event', 'video', '25% video played', videoTitle)
sessionStorage.setItem('one', null)
case sessionStorage.getItem('two'):
ga('send', 'event', 'video', '50% video played', videoTitle)
sessionStorage.setItem('two', null)
case sessionStorage.getItem('three'):
ga('send', 'event', 'video', '75% video played', videoTitle)
sessionStorage.setItem('three', null)
}
}

function videoPlay () {
ga('send', 'event', 'video', 'video played', videoTitle)
setKeyFrames(this.duration)
}

function videoPause () {
ga('send', 'event', 'video', 'video paused', videoTitle)
}

function videoTimeUpdate () {
ga('send', 'event', 'video', '25% video played', '50% video played', '75% video played', videoTitle)
}

function videoTimeUpdate () {
ga('send', 'event', 'video', '25% video played', videoTitle)
}

function videoTimeUpdate () {
ga('send', 'event', 'video', '50% video played', videoTitle)
}

function videoTimeUpdate () {
ga('send', 'event', 'video', '75% video played', videoTitle)
}

function videoEnd () {
ga('send', 'event', 'video', '100% video played', videoTitle)
}
</script>

最佳答案

请注意,仅此代码即使是固定的也行不通。网上有一个非常好的教程,但您似乎找错了。我会尽力为您简化流程。

首先让我们修复原始问题中的代码:

<script type="text/javascript">
document.addEventListener('DOMContentLoaded', init, false)
var videoId = document.getElementById('bigvid3')
//var videoTitle = videoId.getAttribute('data-description')
var videoTitle = 'bigvid3'

function init () {
videoId.addEventListener('ended', videoEnd, false)
videoId.addEventListener('timeupdate', videoTimeUpdate, false)
videoId.addEventListener('play', videoPlay, false)
videoId.addEventListener('pause', videoPause, false)
}

function setKeyFrames (duration) {
var quarter = (duration / 4);
sessionStorage.setItem('one', quarter);
sessionStorage.setItem('two', (quarter * 2));
sessionStorage.setItem('three', (quarter * 3));
}

function videoTimeUpdate () {
var curTime = videoId.currentTime.toFixed(1)

if (curTime > sessionStorage.getItem('one') && sessionStorage.getItem('one') != null) {
ga('send', 'event', 'video', '25% video played', videoTitle)
sessionStorage.setItem('one', null)
} else if (curTime > sessionStorage.getItem('two') && sessionStorage.getItem('two') != null) {
ga('send', 'event', 'video', '50% video played', videoTitle)
sessionStorage.setItem('two', null)
} else if (curTime > sessionStorage.getItem('three') && sessionStorage.getItem('three') != null) {
ga('send', 'event', 'video', '75% video played', videoTitle)
sessionStorage.setItem('three', null)

}


function videoEnd () {
ga('send', 'event', videoCategory, '100% video played', videoTitle);

}

function videoPlay () {
ga('send', 'event', videoCategory, 'video played', videoTitle);

setKeyFrames(this.duration);
}

function videoPause (video) {
var pauseCurTime = videoId.currentTime,
pauseDuration = videoId.duration;
ga('send', 'event', videoCategory, 'video paused', videoTitle);
}
</script>

下一步是在找到视频的页面的开始正文标记之后添加 google 标记管理器标记:

<!-- Google Tag Manager -->
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=emblem"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','emblem');</script>
<!-- End Google Tag Manager -->

一旦正确设置了 google 标签管理器以触发/引发事件,请确保将世界标志替换为页面左上角的实际 google 标签管理器标志。

最后添加此标记以获得您正在寻找的功能:

<script>
// Let's wrap everything inside a function so variables are not defined as globals
(function(){
// This is gonna our percent buckets ( 25%-75% )
//Change the variable "divisor" to create different multiples to track smaller %'s like 10% etc.
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 GTM
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': 'gaEvent',
'gaEventCategory': 'HTML5 Video',
'gaEventAction': 'Progress_' + videos_status[e.target.id].greatest_marker + '%',
// We are using sanitizing the current video src string, and getting just the video name part
'gaEventLabel': 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': 'gaEvent',
'gaEventCategory': 'HTML5 Video',
'gaEventAction': 'Play',
'gaEventLabel': 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':
dataLayer.push({
'event': 'gaEvent',
'gaEventCategory': 'HTML5 Video',
'gaEventAction': 'Pause',
'gaEventLabel': decodeURIComponent(e.target.currentSrc.split('/')[e.target.currentSrc.split('/').length - 1]),
'gaEventValue': videos_status[e.target.id].current
});
break;
// If the user ends playing the video, an Finish video will be pushed ( This equals to % played = 100 )
case 'ended':
dataLayer.push({
'event': 'gaEvent',
'gaEventCategory': 'HTML5 Video',
'gaEventAction': 'Finished',
'gaEventLabel': 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 :)
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>

您需要将此标记添加到 google 标签管理器而不是找到视频的页面并设置参数。

这是 this tutorial 的简化版本.如果你做对了,你会得到你需要的。

最后一件事。我认为 videoEnd 绝对没有问题。它应该工作。确保您的视频没有设置为 LOOP,否则它永远不会结束,也不会注册。除此之外,我看不出它不会注册的任何其他可能性。

关于javascript - 如何修复无法正常工作的 HTML5 视频 Javascript 跟踪代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39040710/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com