JavaScript Event-Tracking

Event-Tracking mit und ohne Google

[im Moment nur für http]
[im Moment nur für http]

[nicht nur für http]

In diesem Beispiel werden Aufrufe von externen Links, sprünge auf Sprungmarken, mailto, tel, Downloads, Videos und Audios als auch Ereignisse wie Scrollen auf der Seite oder Verlassen der Seite selbst das umschalten auf einen anderen Tab über XMLHttpRequest (Ajax) an den Server (aufgerufene Adresse) zurückgemeldet. Eine Routine auf dem Server kann dann einfach an Hand der POST Parameter die Zugriffe analysieren.

GoogleAnalytics Code und die Event-Tracking Erweiterung JavaScript (693 Bytes) 09.05.2020 16:08
//coding: utf-8
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();
  a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXXX-X', 'auto');
ga('require', 'displayfeatures');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');

// activate GA event tracking
// Copyright 2016 Udo Schmal www.gocher.me
// https://www.gocher.me/Event-Tracking
(function(){
  var s=document.createElement('script');
  s.src='/code/tracking.js';
  document.body.appendChild(s);})();
Matomo Code und die Event-Tracking Erweiterung JavaScript (702 Bytes) 09.05.2020 16:08
//coding: utf-8
var _paq = window._paq || [];
_paq.push(['trackPageView']);
_paq.push(['enableLinkTracking']);
(function (matomo_url, matomo_siteId)
  _paq.push(['setTrackingUrl', matomo_url + 'matomo.php']);
  _paq.push(['setSiteId', matomo_siteId]);
  var script = document.createElement('script');
  script.async = true;
  script.defer = true;
  script.src = matomo_url + 'piwik.js';
  document.body.appendChild(script);
}) ('https://matomo.mydomain.de/', 1);

// activate Matomo event tracking
// Copyright 2019 Udo Schmal www.gocher.me
// https://www.gocher.me/Event-Tracking
(function(){
  var s=document.createElement('script');
  s.src='/code/tracking.js';
  document.body.appendChild(s);})();
Art Kategorie Aktion Label Wert
externe Links external click url des Links 1
Sprung zu einer Sprungmarke internal click id der Sprungmarke 1
E-Mail mailto: Link email click E-Mail-Adresse 1
Telefonnummer telefone click Telefonnummer 1
Download Link download click url der Datei 1
Button Klick button click id - Caption 1
Input Type Button Klick input-[type] click id - Value 1
Video Start video play url des Videos 0
Video Pause video pause url des Videos 0
Video Beendet video ended url des Videos Zeit in Sekunden
Audio Start audio play url der Audiodatei 0
Audio Pause audio pause url der Audiodatei 0
Audio Beendet audio ended url der Audiodatei Zeit in Sekunden
Anzeige der Seite Time on Page show url der Seite 0
Seite nicht mehr sichtbar, z.B. neuer Tab Time on Page hide gemessene sichtbare Zeit in ms 0
Verlassen der Seite Time on Page leave gemessene gesamte sichtbare Zeit in ms Zeit in Sekunden
Scroll Event Scroll Depth Percentage Baseline, 25%, 50%, 75%, 100% 1
Code:
tracking.js JavaScript (8,48 kByte) 27.03.2020 15:44
// coding: utf-8
/** Created by: Udo Schmal | https://www.gocher.me/ */

/* Extend tracking with events:
 * time on page
 * scroll depth
 * video/audio play, pause, ended
 * button/input/link click (downloads, external links, internal jump to anchor, emails, phone)
 */

// my analytics
// send event to own analyser
/*
function mya(type, category, action, label, value) {
  var xhr;
  try {
    xhr = new XMLHttpRequest();
    if (xhr) {
      xhr.onreadystatechange = function (){};
      // on my server each location can get analytics events
      xhr.open('post', window.location.pathname);
      xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
      xhr.send('cmd=' + type + '&category=' + category + '&action=' + action + '&label=' + label + '&value=' + value );
    }
  } catch (e) { };
}
*/

(function() {
  'use strict';
  function Analyse() {
    this.scrollTrue = false;
    this.scroll25 = false;
    this.scroll50 = false;
    this.scroll75 = false;
    this.scroll100 = false;
    this.winHeight = null;
    this.docHeight = null;
    this.totalTime = 0;
    this.startTime = null;
    var base = document.getElementsByTagName('base');
    this.baseHref = (base.length > 0 ? base[0].href : window.location.protocol + '//' + window.location.host);
  }

  Analyse.prototype = {
    send: function (type, category, action, label, value) {
      // console output
      console.log('send("' + type + '", "' + category + '", "' + action + '", "' + label + '", "' + value + '");');
      if (ga) {
        // send events to google analytics
        ga('send', type, category, action, label, value);
      } else if (_paq) {
        // send events to matomo
        _paq.push(['trackEvent', action, label, category, value]);
      } else if (mya) {
        // send events to own analytics
        mya(type, category, action, label, value);
      }
    },
    resize: function () {
      var body = document.body, doc = document.documentElement;
      this.winHeight = window.innerHeight || doc.clientHeight || body.clientHeight;
      this.docHeight = Math.max(body.scrollHeight, body.offsetHeight, doc.clientHeight, doc.scrollHeight, doc.offsetHeight);
    },
    scroll: function () {
      var scrollPos = (typeof(window.pageYOffset) == 'number') ? window.pageYOffset : doc.scrollTop;
      var scrollPer = (scrollPos / (this.docHeight - this.winHeight)) * 100;
      if ((scrollPer > 90) && !this.scroll100) {
        this.scroll100 = true;
        this.send('event', 'Scroll Depth', 'Percentage', '100%', 1);
      } else if ((scrollPer > 75) && !this.scroll75) {
        this.scroll75 = true;
        this.send('event', 'Scroll Depth', 'Percentage', '75%', 1);
      } else if ((scrollPer > 50) && !this.scroll50) {
        this.scroll50 = true;
        this.send('event', 'Scroll Depth', 'Percentage', '50%', 1);
      } else if ((scrollPer > 25) && !this.scroll25) {
        this.scroll25 = true;
        this.send('event', 'Scroll Depth', 'Percentage', '25%', 1);
      } else if ((scrollPer > 120) && !this.scrollTrue) {
        this.scrollTrue = true;
        this.send('event', 'Scroll Depth', 'Percentage', 'Baseline', 1);
      }
    },
    timeOnPage: function (event) {
      var type = event.type, value = 0;
      if (type === 'unload') {
        var diffTime = (this.startTime ? new Date().getTime() - this.startTime : 0);
        value = Math.round((this.totalTime + diffTime) / 1000);
      } else {
        if (document.hidden) {
          var diffTime = (this.startTime ? new Date().getTime() - this.startTime : 0);
          this.totalTime = this.totalTime + diffTime;
          this.startTime = null;
          type = 'hide';
        } else {
          this.startTime = new Date().getTime();
          type = 'show';
        }
      }
      this.send('event', 'Time on Page', type, window.location.pathname, value);
    },
    click: function (event) {
      var el = event.target;
      var href, path, isThisDomain, category = null, label = null;
      switch (el.tagName.toLowerCase()) {
      case 'a':
        href = el.getAttribute('href');
        if (href === undefined) {
          href = "";
        } else {
          path = href.split('?')[0];
          isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
          if (!href.match(/^javascript:/i)) {
            if (href.match(/^mailto\:/i)) {
              category = 'email';
              label = path.replace(/^mailto\:/i, '');
            } else if (href.match(/^#/i)) {
              category = 'internal';
              label = href.replace(/^#/i, '');
            } else if (path.match(/\.(zip|7z|exe|dmg|pdf|docx?|xlsx?|pptx?|mp3|txt|rar|wma|mov|avi|wmv|flv|wav|vcf)$/i)) {
              category = 'download';
              label = path.replace(/ /g, "-");
            } else if (href.match(/^https?\:/i) && !isThisDomain) {
              category = 'external';
              label = href.replace(/^https?\:\/\//i, '');
            } else if (href.match(/^tel\:/i)) {
              category = 'telephone';
              label = href.replace(/^tel\:/i, '');
            }
          }
        }
        break;
      case 'button':
        category = 'button[' + el.getAttribute('type') + ']';
        label = (el.getAttribute('id') ?  el.getAttribute('id') + ' - ' : '') + el.textContent || el.innerText;
        break;
      case 'input':
        category = 'input[' + el.getAttribute('type') + ']';
        label = (el.getAttribute('id') ?  el.getAttribute('id') + ' - ' : '') + el.value;
        break;
      }
      if (category !== null) {
        this.send('event', category, event.type, label, 1);
        if ((el.tagName === 'a') && (el.getattribute('target') === undefined || el.getattribute('target').tolowercase() !== '_blank')) {
          setTimeout(function() { location.href = href; }, 400);
          return false;
        }
      }
    },
    mediaEvent: function (event) {
      var el = event.target;
      var src = el.currentSrc;
      src = src.replace(this.baseHref, '');
      src = src.replace(/^https?\:\/\//i, '');
      this.send('event', el.tagName.toLowerCase(), event.type, src || el.id, Math.round(el.currentTime));
    },
    iterate:  function (el) {
      var self = this, childs;
      el = el || document.body;
      if (el.nodeType === 1) {
        switch (el.tagName.toLowerCase()) {
          case "a": // init link click tracking
            if (el.getAttribute('href')) {
              if ((el.getAttribute('href') !== undefined) && (el.getAttribute('href').indexOf('javascript:') === -1)) {
                el.addEventListener('click', function (event) { self.click(event); }, false);
              }
            }
            break;
          case "button": // init button click tracking
            el.addEventListener('click', function (event) { self.click(event); }, false);
            break;
          case "input": // init input type button click tracking
            if (el.getAttribute('type').match(/(button|image|reset|submit)$/i)) {
              el.addEventListener('click', function (event) { self.click(event); }, false);
            }
            break;
          case "video": // init video  tracking
          case "audio": // init video & audio tracking
            el.addEventListener('play', function (event) { self.mediaEvent(event); }, false);
            el.addEventListener('pause', function (event) { self.mediaEvent(event); }, false);
            el.addEventListener('ended', function (event) { self.mediaEvent(event); }, false);
            break;
        }
        childs = el.firstChild;
        while (childs !== null) {
          if (childs.nodeType === 1) {
            this.iterate(childs);
          }
          childs = childs.nextSibling;
        }
      }
    },
    init: function () {
      this.startTime = new Date().getTime();
      var self = this;
      // init scroll depth tracking
      this.resize();
      window.addEventListener('resize', function () { self.resize(); }, false);
      window.addEventListener('scroll', function () { self.scroll(); }, false);
      // init time on page tracking
      document.addEventListener('visibilitychange', function (event) { self.timeOnPage(event); }, false);
      window.addEventListener('unload', function (event) { self.timeOnPage(event); }, false);
      this.iterate();
    }
  };

  var analyse = new Analyse();
  analyse.init();

})();

Kontakt

Udo Schmal
Udo Schmal

Udo Schmal
Softwareentwickler
Ellerndiek 26
24837 Schleswig
Schleswig-Holstein
Germany




+49 4621 9785538
+49 1575 0663676
+49 4621 9785539
SMS
WhatsApp

Google Maps Profile
Instagram Profile
vCard 2.1, vCard 3.0, vCard 4.0

Service Infos

CMS Info

Product Name:
UDOs Webserver
Version:
0.5.1.217
Description:
All in one Webserver
Copyright:
Udo Schmal
Compilation:
Sun, 10. Nov 2024 00:22:34

Development Info

Compiler:
Free Pascal FPC 3.3.1
compiled for:
OS:Linux, CPU:x86_64

System Info

OS:
Ubuntu 22.04.5 LTS (Jammy Jellyfish)

Hardware Info

Model:
Hewlett-Packard HP Pavilion dm4 Notebook PC
CPU Name:
Intel(R) Core(TM) i5-2430M CPU @ 2.40GHz
CPU Type:
x86_64, 1 physical CPU(s), 2 Core(s), 4 logical CPU(s),  MHz