Search code examples
javascripthtmlgoogle-tag-managerevent-tracking

GTM & Optimize : JS Variable is undefined but in console it works well


I'm trying to show the Google Optimize variant in Google Tag Manager.

I tried to implement it by "Custom JavaScript Variable":

function() {
  var property = window.keys(gaData);
  var experiment_nr = window.keys(window.gaData[property].experiments);
  var experiment_value = window.values(window.gaData[property].experiments).toString()
  if (experiment_value == "") {
    return "0"
  } else {
    return experiment_value
  }
}

This is the result of it:

Custom JavaScript Variable Result

Then I tried to test my code with a 5 sec delayed trigger:

GTM HTML Tag

And this is the result of the DevTools JS console:

DevTools Console result

As you can see, the console does not accept it with GTM but accepts it when I type it manually in.

Can someone help me there?


Solution

  • The answer was actually quite simple.

    Google Optimize uses a cookie called _gaexp. There, you get a string summing up the Google Optimize experiment ID as well as the version at the very end: GAX1.2.wHL2IJUnSg2n8PB4iQH66w.18362.1

    All I had to do was to create a new variable reading the cookie:

    1. New variable
    2. 1st Party Cookie with the cookie name "_gaexp"

    You can of course get the cookie name with JavaScript by simply calling Cookies.get('_gaexp') from the DevTools Console (to check if the cookie value is right)

    The _gaexp value has to be manipulated to isolate the variant:

    1. New variable
    2. Custom JavaScript
    3. Add the following code:
    function (){
      if ({{GA_Optimize_Variable}}=='undefined'){
        return '0'
      } else {
        return {{GA_Optimize_Variable}}.charAt({{GA_Optimize_Variable}}.length-1)
      }
    }
    

    The _gaexp is not existant when Google Optimize leads your traffic to the original variant of the website. Therefore, a if statement is needed.

    Finally, you can use your variable in Google Analytics events and/or dimension.