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:
Then I tried to test my code with a 5 sec delayed trigger:
And this is the result of the DevTools JS console:
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?
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:
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:
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.