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?

asked Apr 5, 2020 at 10:26

Timo Rietveld's user avatar

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

Cristiano Dalbem's user avatar

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

dpatryas's user avatar

dpatryasdpatryas

3693 silver badges12 bronze badges

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 Rietveld's user avatar

Timo RietveldTimo Rietveld

4111 gold badge6 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

  1. Basically the code you use is: dataLayer.push({event: 'event_name'});

  2. Then you setup a tag in GTM for «GA4 event».

  3. Use the event name that you want to see in Google analytics.

  4. 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

Whip's user avatar

WhipWhip

1,85022 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

植植心's user avatar

植植心植植心

3962 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 gtag JS 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

Vladimir Tolstikov's user avatar

4

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

Tron08's user avatar

Solution 1

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!

Solution 2

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.

Solution 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.

Related videos on Youtube

3 Steps to Set Up Google Analytics With Tag Manager (UA)

09 : 55

3 Steps to Set Up Google Analytics With Tag Manager (UA)

Root & Branch Digital Marketing

How To Fix Common Errors in Google Analytics Event Tracking

19 : 05

How To Fix Common Errors in Google Analytics Event Tracking

How to track events in GA 4 Google Analytics 4 | Google Tag Manager Tutorial | GA4 Tutorial

28 : 05

How to track events in GA 4 Google Analytics 4 | Google Tag Manager Tutorial | GA4 Tutorial

DataVinci Analytics Agency

Capture JavaScript errors with Google Tag Manager and report in Google Analytics.

07 : 00

Capture JavaScript errors with Google Tag Manager and report in Google Analytics.

Optizent Digital Marketing and Analytics Academy

Tracking Phone Number Clicks Using Google Tag Manager for Google Analytics 4

10 : 06

Tracking Phone Number Clicks Using Google Tag Manager for Google Analytics 4

Install Google Analytics with Google Tag Manager

09 : 08

Install Google Analytics with Google Tag Manager

GA4 Ecommerce Tracking // How to implement ecommerce tracking with Google Tag Manager for GA4

12 : 23

GA4 Ecommerce Tracking // How to implement ecommerce tracking with Google Tag Manager for GA4

How to Track Custom Events with Google Analytics 4 (and Google Tag Manager)

19 : 57

How to Track Custom Events with Google Analytics 4 (and Google Tag Manager)

Analytics Mania — Google Tag Manager & Analytics

Cài Đặt Google Analytics và GA 4 qua Google Tag Manager - Hướng dẫn cài đặt chi tiết

13 : 17

Cài Đặt Google Analytics và GA 4 qua Google Tag Manager — Hướng dẫn cài đặt chi tiết

How To Set Up Google Analytics With Next.JS (Using Next.JS Script Component)

06 : 02

How To Set Up Google Analytics With Next.JS (Using Next.JS Script Component)

Cài Sự Kiện Chuyển Đổi Trên Google Analytics 4 Kết Hợp Với Google Tag Manager - Update Mới Nhất

14 : 20

Cài Sự Kiện Chuyển Đổi Trên Google Analytics 4 Kết Hợp Với Google Tag Manager — Update Mới Nhất

How to track Custom Dimensions in Google Analytics 4 (2022)

19 : 14

How to track Custom Dimensions in Google Analytics 4 (2022)

Analytics Mania — Google Tag Manager & Analytics

Track Events with GTAG.js in Google Analytics 4

17 : 56

Track Events with GTAG.js in Google Analytics 4

Analytics Mania — Google Tag Manager & Analytics

Event Tracking is not working in Google Tag Manager? Here are the solutions

13 : 00

Event Tracking is not working in Google Tag Manager? Here are the solutions

Analytics Mania — Google Tag Manager & Analytics

How to Set Up a GA4 Form Submission Conversion (With Google Tag Manager)

15 : 45

How to Set Up a GA4 Form Submission Conversion (With Google Tag Manager)

Root & Branch Digital Marketing

Comments

  • 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?

  • Hi Timo, is there any chance you could provide a code snippet of the solution? Thanks!

  • I reached this same conclusion. Do you think it’s just an oversight in their docs? It’s super confusing and you end up going round in circles. My browser tells me that GTM loads analytics.js which loads ec.js and GTM also loads gtag/js, but the generated code they give me doesn’t define gtag. What you have above is literally the only way it could possibly work so I have to conclude there’s just a gaping hole in their docs.

  • Also for anyone wondering why this isn’t automatic when you add GA4 to the GTM configuration as a new tag: The script is loaded async, so your page can continue to load — but clearly wherever you want to call the API you don’t want to check ‘is it loaded’ every time. So that’s what dataLayer is, just a list of commands to be executed when it IS ready. And gtag is literally just an alias to push to that list. All my existing code was just doing dataLayer.push because that’s what they tell us to do! developers.google.com/tag-manager/devguide

  • It’s like one day someone said ‘Urm why don’t we just make an alias for dataLayer.push and call it gtag ?’, but not every one got that memo!

Recents

Related

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.

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?

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

Возможно, вам также будет интересно:

  • Gta5 exe ошибка приложения
  • Gta vice city ошибка с0000005
  • Gta vice city ошибка unhandled exception c0000005 at address 004c4017
  • Gta vice city ошибка 640 480
  • Gta vice city definitive edition ошибка при запуске

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии