javascript GA事件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript GA事件相关的知识,希望对你有一定的参考价值。

function gaEventsEventListener() {
  var nodeList = document.querySelectorAll('.ga-event');

  forEach(nodeList, function (index, value) {
    value.addEventListener('click', gaEvent, false);
  });
}

function gaEvent(event) {
  var dataAttrs = this.dataset;
  var eventCategory = dataAttrs['eventCategory'];
  var eventAction = dataAttrs['eventAction'];
  var eventLabel = dataAttrs['eventLabel'];

  if (eventCategory && eventAction && typeof ga === 'function') {
    ga('send', {
      hitType: 'event',
      eventCategory: eventCategory, // required
      eventAction: eventAction, // required
      eventLabel: eventLabel,
      // eventValue: eventValue,
      // hitCallback: function() {
      //   console.log('ga Event, category: "' + eventCategory + '", action: "' + eventAction + '", label: "' + eventLabel + '"');
      // }
    });
  }
}

document.addEventListener('DOMContentLoaded', gaEventsEventListener);
// https://developers.google.com/analytics/devguides/collection/analyticsjs/events

/*
<%= link_to 'link', 'location', class: 'ga-event', data: { event_category: 'Navigation', event_action: 'click', event_label: 'Our Roots' } %>
*/

$(document).on('click', '.ga-event', function(e) {
  var eventCategory = $(this).data('event-category');
  var eventAction = $(this).data('event-action');
  var eventLabel = $(this).data('event-label');
  // var eventValue = $(this).data('event-value');
  
  // Analytics
  if (eventCategory && eventAction && typeof ga === 'function') {
    ga('send', {
      hitType: 'event',
      eventCategory: eventCategory, // required
      eventAction: eventAction, // required
      eventLabel: eventLabel,
      // eventValue: eventValue,
      // hitCallback: function() {
      //   console.log('ga Event, category: "' + eventCategory + '", action: "' + eventAction + '", label: "' + eventLabel + '"');
      // }
    });
  }
  
  // gtag
  if (eventCategory && eventAction && typeof ga === 'function') {
    // https://stackoverflow.com/a/29434548
    var trackerName = ga.getAll()[0].get('name');
    ga(trackerName + '.send', {
      hitType: 'event',
      eventCategory: eventCategory, // required
      eventAction: eventAction, // required
      eventLabel: eventLabel,
      transport: 'beacon',
      // eventValue: eventValue,
      // hitCallback: function() {
      //   console.log('ga Event, category: "' + eventCategory + '", action: "' + eventAction + '", label: "' + eventLabel + '"');
      // }
    });
  }
});

以上是关于javascript GA事件的主要内容,如果未能解决你的问题,请参考以下文章

javascript 触发电话链接的GA事件

javascript GA-所有事件,track.js

javascript 测试GA表单/事件跟踪

javascript GA事件

javascript 表单提交中的GA事件 - 多种形式

javascript jQuery 1.7+中锚点的GA事件