javascriptgoogle-analytics-apigoogle-optimize

Is it possible to read ExperimentId and VariationId in Javascript with Google Optimize?


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?


Solution

  • 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