Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Analytics Web+App event config: Error 'gtag is not defined'

I'm trying to setup ecommerce event configuration of Google Analytics App+Web for a website. Refer to the documentation here.

Because there is a lot of custom code for the ecommerce configuration, I cannot use the general GA App+Web webevent template, so instead I'm using a custom HTML-tag in this case.

As a first test, I tried to fire the following simple event:

<script>

  gtag('event', 'blabla', {
  'test_param1': 'test_value_1'
});

</script>

However, the event is not correctly sent to GA; instead, the following error in the console is returned:

Uncaught ReferenceError: gtag is not defined

To reproduce, see the following page: https://www.hema.nl/mooi-gezond/make-up/make-up-accessoires/toilettassen-1/toilettas-11830901.html

Additional information:

  • The GA App+Web base initialization is (successfully) done via GTM, via the GA App+Webconfiguration template tag.
  • I also configured a few other (simple non-ecommerce) GA App+Web events via GTM via the GA App+Web webevent template tag , and these events are sent to GA successfully.

Does anyone know what's going wrong, why the console error appears and why the event is not sent to GA?

like image 641
Timo Rietveld Avatar asked Apr 05 '20 10:04

Timo Rietveld


2 Answers

Short answer

Additionally to the GTM GA App+Web tag, you need to add the following code to have gtag() defined:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
</script>

Long answer

According to the official documentation (https://developers.google.com/analytics/devguides/collection/ga4) this is the code you should include in your site:

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

  gtag('config', 'MEASUREMENT_ID');
</script>

After inspecting a website with this tag I found GTM has injected that first line, which is enough to make analytics work. But it didn't add the other lines, some of which effectively defines the gtag global function as a "syntax sugar" for pushing things to the Analytics Data Layer.

Personally, I find this really strange, since using GTM is the most cannonical of adding Google Analytics to a website and it's by the same company.

like image 88
Cristiano Dalbem Avatar answered Sep 16 '22 16:09

Cristiano Dalbem


In my case Uncaught ReferenceError: gtag is not defined was caused by uBlock/adblock turned on.

I think it's worth testing if accepted answer doesn't work.

like image 23
dpatryas Avatar answered Sep 17 '22 16:09

dpatryas