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?
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
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.
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.
EDIT: Nevermind my cookie-based answer below, I found a better solution.
Just do this:
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:
The experiment id is the part after the second number:
The variation id is the last number:
I wrote this code to extract it from the cookie:
WARNING: Fetching the experiment ID and variationId from the cookie is not a good idea. For two reasons.
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.
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:
(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:
If you want to find both the experimentId and variation you can register a callback for any experiment:
For more details
https://support.google.com/optimize/answer/9059383
I've found that the variant number can be obtained running a code like:
The result should be "0"for the original, "1" for the first variant...
You can get the experiments with:
Of course you have to replace UA-XXXXXXXX-X for the Google Analytics ID and ZYkOuNLKEoeLytt-dLWw3x for your experiment id.