javascriptgoogle-analyticscustom-dimensions

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?


Solution

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