Matomo Engagement Analytics

by nathanlogan

HTML

<!-- Matomo -->
  <script type="text/javascript">
    const getPages = function() {
      const contentHeight = document.body.offsetHeight
      const viewport = window.innerHeight
      const scrollY = window.scrollY

      const pagesOfScroll = Math.floor(contentHeight / viewport)
      let currentPage = Math.round(scrollY / viewport + 1)
      currentPage = currentPage > 0 ? currentPage : 1

      return {
        pages: pagesOfScroll,
        current: currentPage
      }
    }

    const getWordCount = function() {
      const textContainers = document.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, button')
      let total_words = 0
      for (i = 0; i < textContainers.length; i++) {
        total_words += textContainers[i].textContent.trim().split(/\W+/).length
      }
      return total_words
    }

    let currentHeight = 0
    let currentScrollY = 0
    let currentWordCount = 0

    const throttle = function (fn, threshhold, scope) {
      threshhold || (threshhold = 250);
      var last, deferTimer;
      return function () {
        var context = scope || this;
        var now = +new Date;
        var args = arguments;
        if (last && now < last + threshhold) {
          // hold on to it
          clearTimeout(deferTimer);
          deferTimer = setTimeout(function () {
            last = now;
            fn.apply(context, args);
          }, threshhold);
        } else {
          last = now;
          fn.apply(context, args);
        }
      };
    }
    const sendActivity = function() {
      const docH = (document.height !== undefined) ? document.height : document.body.offsetHeight;
      const scrollY = window.scrollY
      const wordCount = getWordCount()
      let heightHasBeenSet = false
      let scrollHasBeenSet = false
      let wordCountHasBeenSet = false

      if (!heightHasBeenSet || currentHeight !== docH) {
        currentHeight = docH
        heightHasBeenSet = true
        _paq.push(['setCustomDimension', customDimensionId = 1,...