sabotenramen1
sabotenramen1

Reputation: 15

Problem retrieving Google Analytics Tracker Name using Javascript

I use Google Tag Manager to implement Google Analytics. Thus, the tracker names initiated on my site are not always the same eg. gtm2, gtm3.

The overall objective is to be able to send data to my custom metric as follows:

ga( 'gtm2.set', 'metric2', 'custom metric data');

I can't figure out why this code would not work:

var yone = (ga.getAll()[1].get("name"));
var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');

The error in Javascript console is that "VM3324:1 Uncaught TypeError: ga.getAll is not a function". I am not sure why this is showing since when I do console.log(ga.getAll()[1].get("name"));, the correct tracker name shows up in console log ie. gtm2.

EDIT I tried out introducing the callback function as mentioned by @balexandre so my code became this:

var yone = ga(function() {
ga.getAll()[1].get("name")});
var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');

In this instance, console now shows a different error message "Uncaught TypeError: Cannot read property 'concat' of undefined".

Thanks.

Upvotes: 0

Views: 685

Answers (2)

balexandre
balexandre

Reputation: 75113

it's a callback, so, you can't just call your code and hope all will work, it will not!

you tried this

var yone = ga(function() {
  ga.getAll()[1].get("name")
});

var ytwo = ".set";
var ythree = yone.concat(ytwo);
ga( ythree, 'metric2', 'custom metric data');

but when you're in line var ytwo you don't have anything in yone yet, the call not yet fired... hence it's a callback (will only execute the code when the script is loaded), you don't know if it takes 1ms or 10 sec...

so, you should try:

ga(function() {
  // debugger;
  var yone = ga.getAll()[1].get("name");
  var ytwo = ".set";
  var ythree = yone.concat(ytwo);
  ga( ythree, 'metric2', 'custom metric data');
});

and if you want, remove the comment and use the browser debugger to check all existing variables and execute the code, inside the callback...

Upvotes: 1

Michele Pisani
Michele Pisani

Reputation: 14197

Have you tried with index 0 instead 1? Like this:

ga.getAll()[0].get("name");

The result if you not use GTM could be t0, with GTM could be gtmxx.

Upvotes: 0

Related Questions