🏠 back to Observable

Embedding Google Analytics - good or evil - poll


#1

I was wondering what the admins and the community think about it when one would start adding google tracking code in their notebook like so:

html`<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-XXXXXX-XX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-XXXXXX-XX');
</script>`

I’m not sure if that would even work correctly but I’m interested in opinions, per poll or per comment :slight_smile: :

  • Seems ok :slight_smile:
  • That’s evil :fearful: !!
  • No idea, but interested to see what others think.

0 voters


#2

SCRIPT elements aren’t evaluated by the html tagged template literal, so you’ll want to use JavaScript (and typically require) to load libraries such as Google Analytics. Here’s a quick demonstration of Google Analytics in Observable:


#3

Thanks Boss! Based on your suggestion I ended up doing this:

  pageAnalytics = {
    const id = 'UA-XXXXXX-XX';
    await require(`https://www.googletagmanager.com/gtag/js?id=${id}`).catch(() => {});
    const dataLayer = window.dataLayer = window.dataLayer || [];
    gtag('js', new Date());
    gtag('config', id);
    return md`This page uses ***Google Analytics***, see: [Terms of Service](https://www.google.com/analytics/terms/)`;
    function gtag() { dataLayer.push(arguments); }
  }

Looks like all pages are reported as ‘/worker/worker.7352fb1a7c…53e60b20e6e912a2599e.html’ not sure yet how to fix this.
Perhaps this could be built into Observable, so that users just need to provide their id?


#4

You can determine the page URL like so:

html`<a href>`.href

Or the path:

html`<a href>`.pathname

For example:

ga("send", "pageview", html`<a href>`.pathname)

#5

The gtag version works fine now, (big thanks to @mike).

  pageAnalytics = {
    const id = 'UA-XXXXXX-XX';
    await require(`https://www.googletagmanager.com/gtag/js?id=${id}`).catch(() => {});
    const dataLayer = window.dataLayer = window.dataLayer || [];
    const location = html`<a href>`;
    gtag('js', new Date());
    gtag('config', id, {
      'page_path': location.pathname,
      'page_location' : location.href
    });
    return md`<sup>[Google Analytics](https://www.google.com/analytics/terms/). Perhaps consider removing/[replacing analytics with your own](https://beta.observablehq.com/@peter-hartmann/page-analytics).</sup>`;
    function gtag() { dataLayer.push(arguments); }
  }

Forkable notebook with usage instructions: @peter-hartmann/page-analytics


#6

Have you explored alternative analytics options to Google? (aside: my uBlock/uMatrix settings will surely mess up your analytics anyway)