0

I am new to google analytics tag, I am sending event on click, now I have added data-consent as you can see below my script tag in a header.

Tag

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>my app</title>


 <!-- Global site tag (gtag.js) - Google Analytics -->
<script async  type="text/plain" data-consent-category="3" src="gtagjs link"></script>
<script type="text/plain" data-consent-category="3">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'my code');
</script>

Sending event to GTA

if(gtag){
    console.log('GTA IS LOADED');
    gtag('event', "take_test", {
        'event_category': "engagement",
        'event_label': labela,
    });
}else{
    console.log('NO GTA IS NOT LOADED');

}

When I run my app I get the following

gtag is not defined

The Dead Man
  • 4,997
  • 13
  • 71
  • 119
  • Does this answer your question? [JavaScript check if variable exists (is defined/initialized)](https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized) – kmoser Dec 10 '20 at 16:12

1 Answers1

0

This is your current snippet:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async  type="text/plain" data-consent-category="3" src="gtagjs link"></script>
<script type="text/plain" data-consent-category="3">
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'my code');
</script>

I am sure that you replaced gtagjs link to hide the ID, however the text/plain type attribute is definitely wrong because the code doesn't recognize as JavaScript but as text. As a result it does not load the library and gives you the error gtag is not defined.

So, or you replace the snippet with the following (with your ID instead of you replaced):

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

or you have to use text/plain for the event too (if you want to block Analytics without consent):

<script type="text/plain">
    gtag('event', 'take_test', {
        'event_category': 'engagement',
        'event_label': labela,
    });
</script>
Michele Pisani
  • 10,406
  • 3
  • 15
  • 33