Daniel Santos
Daniel Santos

Reputation: 15778

Entire script for Google Analytics for tracking custom dimensions on JS

I was having issues for traking custom dimensions with our GA. I have found several pieces of sample code in official documentation and some blogs. All of them are different of each ther.

By the end, i'd implemented the fallowing piece of code:

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

  gtag('send', 'pageview', { 'semana':'semana 11' }); // first attempt 

  gtag('event', 'pageview', { 'semana':'semana 12' }); // second attempt 

  ga('set', 'dimension1', 'semana 3'); // third attempt. ERROR: ga is not defined

</script>

(where xxxxxx ir our Id.)

I also create a custom dimension in the GA account. however I cant see track the custom dimension created. I suspect that those events are not sent to the GA.

Am I doing something wrong? Im not able to see our custom dimensions tracked by the GA, as seen below (yeelow mark is the custom dimension)

enter image description here

In this case, what are the full Javascript code that allows me to track a properly a custom dimension in our website?

Upvotes: 1

Views: 861

Answers (2)

Daniel Santos
Daniel Santos

Reputation: 15778

What works for me was.

<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-xxxxxx-1', 'auto');
ga('set', 'dimension1', 'semana 3');
ga('send', 'pageview');

</script>

Upvotes: 0

Michele Pisani
Michele Pisani

Reputation: 14179

Are you sure the custom dimension on Analytics has id '1'?

Your first example generates an error because the code is of gtag() and you call ga() that does not exist, but the second code should work properly.

Upvotes: 1

Related Questions