I have created an A/B-test using Google Optimize. Now I would like to read the current experimentId and variationId in Javascript. My goal is to run different javascript based on the given variation.
I can't seem to find any info on this in the documentation. Is it possible?
EDIT: Nevermind my cookie-based answer below, I found a better solution.
Just do this:
var propertyId = "UA-1234567-33";
var experimentId = Object.keys(gaData[propertyId].experiments)[0];
var variationId = gaData[propertyId].experiments[experimentId];
(Don't do this.. keeping it here for reference)
Maximes answer is working but was not exactly what I was looking for. I wanted to be able to find the experimentId and variationId without adding code through the visual editor. I finally found a way.
The values are actually stored in the _gaexp cookie. The cookie is present when an experiment is running. You can inspect it in Chrome by opening Developer tools, going to the Application tab and clicking Cookies in the left pane. It looks something like this:
GAX1.2.S1SJOWxJTVO9tM2QKV3NcP.17723.1
The experiment id is the part after the second number:
S0SJOWxJTVO1tM2QKD2NcQ
The variation id is the last number:
1
I wrote this code to extract it from the cookie:
function getCookieValue(cookieName) {
var result = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return result ? result.pop() : '';
}
function getExperimentId() {
var cookie = getCookieValue('_gaexp');
if (cookie == undefined) {
return undefined;
} else {
var fields = cookie.split('.');
return fields[2];
}
}
function getVariationId() {
var cookie = getCookieValue('_gaexp');
if (cookie == undefined) {
return undefined;
} else {
var fields = cookie.split('.');
return fields[4];
}
}
var experimentId = getExperimentId();
var variationId = getVariationId();
WARNING: Fetching the experiment ID and variationId from the cookie is not a good idea. For two reasons.
GAX1.2.S1SJOWxJTVO9tM2QKV3NcP.17723.1!vr1mB2L2RX6kSI1ZnUDTzT.18721.0
which is the same as how it would look if you were running to experiments at once. It makes it hard to reason about what experimentId to use.