-->

Is it possible to read ExperimentId and VariationI

2019-03-14 15:01发布

问题:

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?

回答1:

Now there is also the Google Optimize javascript API available that is a better option:

The experimentId is now available in the Optimize UI, as soon as the experiment is created (before start).

The API is already available in the page and you can use it like this:

google_optimize.get('<experimentId>');

(note: this will work only after the Optimize container script has been loaded)

You can also register a callback to run the javascript that you want at any time (even before the Optimize script has been loaded) using:

function gtag() {dataLayer.push(arguments)}

function implementExperimentA(value) {
  if (value ==  '0') {
    // Provide code for visitors in the original.
  } else if (value == '1') {
    // Provide code for visitors in first variant.
  }

gtag('event', 'optimize.callback', {
    name: '<experiment_id_A>',
    callback: implementExperimentA
 });

If you want to find both the experimentId and variation you can register a callback for any experiment:

function implementManyExperiments(value, name) {
  if (name == '<experiment_id_A>') {
    // Provide implementation for experiment A
    if (value ==  '0') {
      // Provide code for visitors in the original.
    } else if (value == '1') {
      // Provide code for visitors in first variant.
    ...
  } else if (name == '<experiment_id_B>') {
    // Provide implementation for experiment B
    ...
}

gtag('event', 'optimize.callback', {
    callback: implementManyExperiments
 });

For more details

https://support.google.com/optimize/answer/9059383



回答2:

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];

Old answer:

(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.

  1. When the experiment is finished, the cookie is still present. The cookie is cached, so you will find an experimentId and variationId that does not apply, and you can not know if the experiment is running or not.
  2. If you stop experiment A, and start experiment B, the old value for A will still be part of the cookie. So it will look something like this:

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.



回答3:

Google Optimize allow you to run arbitrary JS on a per DOM element basis.

This feature is meant to modify the DOM elements, but there's nothing stopping you from using it to call a JS function or define some variables.

How to set up the script

  1. Edit your experiment variant in the Visual Editor.
  2. Click on the Select elements icon (the rectangle in the top left corner)
  3. In the Element Selector field, type in body.
  4. Click the Add change button and select Javascript. This will bring up a dialog that allows you to input a JS function that will be called for the body.
  5. Put in the code you want to run in there.

What code to run

Assuming you have a doSomething() method define on your page, you can have your Google Optimized function look something like this:

doSomething("Experiment #1", "Variant A");

Alternatively, you can try defining your variables globally.

// We need to use `windows` here, because if we define a variable 
// with `var`, it will be limited to the scope of the Google Optimize
// function.
window["google_optimize_exp_id"] = "Experiment #1";
window["google_optimize_exp_var_id"] = "Variant A";

If you use the second method, keep in mind that you need to wait until the Google Optimized function has run before running your own logic.



回答4:

I've found that the variant number can be obtained running a code like:

gaData["UA-XXXXXXXX-X"].experiments['ZYkOuNLKEoeLytt-dLWw3x']

The result should be "0"for the original, "1" for the first variant...

You can get the experiments with:

gaData["UA-XXXXXXXX-X"].experiments

Of course you have to replace UA-XXXXXXXX-X for the Google Analytics ID and ZYkOuNLKEoeLytt-dLWw3x for your experiment id.