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?
asked Apr 5, 2020 at 10:26
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.
answered Feb 21, 2021 at 13:27
3
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.
answered Oct 4, 2021 at 8:58
dpatryasdpatryas
4094 silver badges13 bronze badges
This may be a bit of a repeat of the accepted answer, but I wanted to confirm that it is indeed recommended by (some) Google documentation to manually add the following snippet of code to the <head> section of your website, just above your existing Tag Manager container snippet:
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
</script>
This is necessary if:
- You are deploying your Analytics Tags using Google Tag Manager rather than the «Google Tag»
- You wish to utilize the gtag() syntax to send Events to your GA4 Analytics property
Source: https://developers.google.com/analytics/devguides/migration/ecommerce/gtm-ga4-to-ua#4_enable_the_gtagjs_api
answered Feb 7 at 22:33
The cause of the problem has been found. The problem seemed to be that gtag() does not work if the App+Web base setup is done with the GTM App+Web base template tag. Instead, an event should first be pushed to the GTM datalayer, and then the GTM App+Web event template should be used to send the event to Google Analytics.
Lots of thanks Gino (working at Merkle) for fixing the issue!
answered Apr 7, 2020 at 12:48
Timo RietveldTimo Rietveld
4612 gold badges6 silver badges20 bronze badges
1
If you’re using Google Tag Manager, the gtag function doesn’t exist. Follow this guide to create custom events
-
Basically the code you use is:
dataLayer.push({event: 'event_name'}); -
Then you setup a tag in GTM for «GA4 event».
-
Use the event name that you want to see in Google analytics.
-
For the trigger, use custom event. Here, in the event name, use the name that you used in your code
event_name
answered Oct 31, 2021 at 15:14
WhipWhip
1,90122 silver badges43 bronze badges
0
I found out that it was due to an AD Blocking Extensions added to my chrome
answered Feb 19, 2022 at 13:41
植植心植植心
4063 silver badges5 bronze badges
2022 Year answer:
For anyone struggling with using GA4 gtag and GTM (Google Tag Manager) simultaniously in your SPA/Angular/React app, you should do next:
- don’t use built-in GTM’s «Google Analytics: GA4 Configuration» tag configuration
- do use «Custom HTML» GTM tag with exactly that
gtagJS code from your Google Analytics, i.e.
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
</script>
After that you can use gtag in your code as you intended to do, all should work. No whole Firebase needed or something. Possibly you will need to have
gtag('config', 'GA_MEASUREMENT_ID', {
send_page_view: false
});
to disable automatic page_view tracking.
answered Apr 12, 2022 at 14:06
4
Tag Manager Help
Sign in
Google Help
- Help Center
- Community
- Tag Manager
- Privacy Policy
- Terms of Service
- Submit feedback
Send feedback on…
This help content & information
General Help Center experience
- Help Center
- Community
Tag Manager
The Google Analytics: GA4 Configuration tag is now the Google tag. GA4 Configuration tags in a web container will be automatically migrated starting in September. There are no changes to your existing measurement and there is no action required from you. Learn more
Had to wrap up the gtag() call to some additional code to fix the issue:
import { isPlatformBrowser } from '@angular/common';
import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
declare var gtag;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(@Inject(PLATFORM_ID) private platformId: Object, public router: Router) {}
ngOnInit() {
const navEndEvent$ = this.router.events.pipe(filter(e => e instanceof NavigationEnd));
navEndEvent$.subscribe((e: NavigationEnd) => {
if (isPlatformBrowser(this.platformId)) {
gtag('config', 'UA-xxxxxxxxx-x', { page_path: e.urlAfterRedirects });
}
});
}
}
If you know more elegant solution or have any plans to improve the particular use case please let me know.
Я пытаюсь настроить конфигурацию событий электронной торговли Google Analytics App + Web для веб-сайта. См. Документацию здесь.
Поскольку для конфигурации электронной коммерции существует много настраиваемого кода, я не могу использовать общий шаблон веб-событий GA App + Web, поэтому вместо этого я использую настраиваемый HTML-тег в этом случае.
В качестве первого теста я попытался запустить следующее простое событие:
<script>
gtag('event', 'blabla', {
'test_param1': 'test_value_1'
});
</script>
Однако событие неправильно отправляется в GA; вместо этого в консоли возвращается следующая ошибка:
Неперехваченная ошибка ссылки: gtag не определен
Для воспроизведения см. Следующую страницу: https://www.hema.nl/mooi-gezond/make-up/make-up-accessoires/toilettassen-1/toilettas-11830901.html
Дополнительная информация:
- Инициализация базы GA App + Web (успешно) выполняется через GTM с помощью тега шаблона GA App + Webconfiguration.
- Я также настроил несколько других (простых не связанных с электронной торговлей) событий GA App + Web через GTM с помощью тега шаблона webevent GA App + Web, и эти события успешно отправляются в GA.
Кто-нибудь знает, что не так, почему появляется ошибка консоли и почему событие не отправляется в GA?
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?
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.
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.
