测量不在视频标签内但在标签内的视频的视频观看行为

时间:2018-12-17 10:28:56

标签: javascript google-analytics

下面是我用来衡量用户何时开始观看视频,观看整个视频或观看25%,50%或75%的代码。然后将信息发送到GA。此代码用于视频标签中的视频。但是,如何更改此代码以使其与<a>这样的<a data-type="iframe" data-src="video1.mp4"><img src="someimage.png"></a>标记内的mp4一起使用。

(function() {
  document.addEventListener('DOMContentLoaded', init, false);
  var videoId, dur, quarter, stat;

  function init() {
    for (var video of document.querySelectorAll('video')) {
      video.addEventListener('play', videoPlay, false);
      video.addEventListener('ended', videoEnd, false);
      video.addEventListener('timeupdate', videoTimeUpdate, false);
    }
  }

  function setKeyFrames(duration) {
    if (dur) {
      return;
    }
    dur = duration;
    quarter = duration / 4;
  }

  function videoTimeUpdate(e) {
    var videoId = e.target;
    var curTime = videoId.currentTime;
    if (curTime >= quarter && curTime < quarter * 2 && stat !== 1) {
      gtag('event', 'User Watched 25% Of Video', {
        'event_category': 'Video',
        'event_label': videoId.id
      });
      stat = 1;
    } else if (curTime >= quarter * 2 && curTime < quarter * 3 && stat !== 2) {
      gtag('event', 'User Watched 50% Of Video', {
        'event_category': 'Video',
        'event_label': videoId.id
      });
      stat = 2;
    } else if (curTime >= quarter * 3 && curTime < dur && stat !== 3) {
      gtag('event', 'User Watched 75% Of Video', {
        'event_category': 'Video',
        'event_label': videoId.id
      });
      stat = 3;
    }
  }

  function videoPlay(e) {
    var videoId = e.target;
    gtag('event', 'User Played Video', {
      'event_category': 'Video',
      'event_label': videoId.id
    })
    setKeyFrames(this.duration);
  }


  function videoEnd(e) {
    var videoId = e.target;
    stat = 4;
    gtag('event', 'User Watched ALL Of Video', {
      'event_category': 'Video',
      'event_label': videoId.id
    });
}


})();

0 个答案:

没有答案