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

3593 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,81222 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

I have a global variable in my Typescript file for Google Analytics.

declare var gtag: any;

When I run ng test in my Angular Project it’s showing following error.

ReferenceError: gtag is not defined

Shabbir Dhangot's user avatar

asked Jun 26, 2018 at 11:42

pskkar's user avatar

2

Explanation : Since you are using google tag manager, you have to define the gtag function somewhere. When you followed the tutorial from googleAnalytics they asked you to include some javascript code in your index.html. The problem is when you run your tests you create components without their parents, so the actual index.html file is never loaded neither the javascript code you added. You need to load that code before you run your tests.

How to proceed :
I’d advise you to export that content in a separate file,
then import that file into your index.html

<script src="assets/metrics/gtm.js"></script>

After this go into your Karma.conf.js and below frameworks :[…] add the following :

   files: [
      /* I put my file (containing javascript code) into that path, yours might change */
      { pattern: 'src/assets/**/gtm.js', included: true }
    ],

After this you should be good to simply restart your tests!
Hope it helps someone else!

answered Jul 8, 2020 at 19:11

ItsNotMyFault's user avatar

1

Here’s something that worked for me. I added the following code in a javascript file called src/assets/js/gtag.init.js:

window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

I then added the path to this file in my karma.conf.js file:

files: [
    { pattern: 'src/assets/js/gtag.init.js', included: true }
]

Lastly, I added the path in my angular.json file under tests:scripts:

{
    "test": {
        "scripts": [
            'src/assets/js/gtag.init.js'
        ]
    }
}

This finally made my tests pass, and the error is no longer produced.

answered Feb 20 at 20:14

Christopher Smit'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.

Объяснение : Поскольку вы используете диспетчер тегов Google, вам нужно где-то определить функцию gtag. Когда вы следовали руководству от googleAnalytics, они попросили вас включить некоторый код javascript в ваш index.html. Проблема в том, что когда вы запускаете свои тесты, вы создаете компоненты без их родителей, поэтому фактический файл index.html никогда не загружается, ни добавленный вами код javascript. Вам необходимо загрузить этот код перед запуском тестов.

Как поступить :
Я бы посоветовал вам экспортировать этот контент в отдельный файл,
затем импортируйте этот файл в свой index.html

<script src = "assets/metrics/gtm.js"></script>

После этого войдите в свой Karma.conf.js и ниже: […] добавьте следующее:

   files: [
      /* I put my file (containing javascript code) into that path, yours might change */
      { pattern: 'src/assets/**/gtm.js', included: true }
    ],

После этого вы можете просто перезапустить тесты!
Надеюсь, это поможет кому-то другому!

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

Я пытаюсь настроить конфигурацию событий электронной торговли 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?

Понравилась статья? Поделить с друзьями:
  • Gta5launcher exe ошибка
  • Gta5 ошибка при установке
  • Gta5 exe системная ошибка
  • Gta5 exe ошибка при запуске приложения 0xc0000142
  • Gta критическая ошибка zlib20