Guide to add Google Analytics to notebook

I was wondering if anyone has succeeded in adding Google Analytics to their notebook. I tried this old topic but didn’t manage to make it work, there are no events reaching Google Analytics.

Ideally this should be in Observable’s documentation, and maintained by Observable, since many people need to know if (and how) their work is being used.

Which part of it? The thread discusses several solutions. :slight_smile:

Can you share a notebook that demonstrates your attempt?

I tried this part.

This is my notebook.

And this is what I see in google analytics:

I see more entries in window.dataLayer which suggests that GTM was loaded correctly, but no events are being sent.

It looks like a configuration issue to me. Have you tried manually sending a page_view event? Perhaps this thread contains some helpful hints to narrow down the cause.

1 Like

If this is what you mean “sending a page_view event” (the test option within google analytics), it seems to be working, yes.

No, I meant sending a manual page_view event via gtag(): Measure pageviews  |  Google Analytics  |  Google for Developers

I tried, but no events come through. This is the relevant block (currently in the notebook):

pageAnalytics = {
  await require(`${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
  gtag('event', 'page_view', {
    page_title: '<Page Title>',
    page_location: '<Page Location>'
  return md`<sup>[Google Analytics]( Perhaps consider removing/[replacing analytics with your own](</sup>`;
  function gtag() { dataLayer.push(arguments); }

It’s not that events aren’t coming through - they don’t get sent in the first place, as far as I can tell (you can check via the network tab in your browser’s dev tools).

Your tag manager code runs in a sandboxed iframe, so you may need to investigate what limitations apply there with regard to GA4 and Google Tag Manager.

But events could also not be firing due to a misconfiguration, since the tag manager script encodes your property config.

Thank you for the help @mootari. I’ll keep debugging and will come back to post any updates.

And this also brings back my initial point. I hope that ObservableHQ adds a support article showing how to integrate with GA.