Hi everyone. Have a question regarding Growthbook ...
# ask-questions
i
Hi everyone. Have a question regarding Growthbook installation via GTM and event tracking with GA4 (which is also installed via gtm). Initialization code installed with the SDK (I`ve tried to do it separately with the same results) CSP allows the launch of the script. AA test is launched in a growthbook control panel. The main problem is I can`t send the ga4 event on callback. Secondary problem - I can`t get any info from growthbook debugger (dev mode is on) because it isnt working. What do you think I should do to fix this issue? Has someone already faced this problem?
Copy code
<script id="growthbook-sdk" src="<https://cdn.jsdelivr.net/npm/@growthbook/growthbook/dist/bundles/index.min.js>" defer></script>

<script>
  (function() {
    // Wait for the SDK to load before starting GrowthBook
    if (window.growthbook) {
      startGrowthbook();
    } else {
      document.querySelector("#growthbook-sdk").addEventListener("load", startGrowthbook);
    }

    function startGrowthbook() {
      if (!window.growthbook) return;
      var gb = new growthbook.GrowthBook({
        apiHost: "<https://cdn.growthbook.io>",
        clientKey: "sdk-1231231231",
        // TODO: Add decryptionKey if using encryption
        attributes: {
          cid: "{{clientId}}" // TODO: Read user/device id from a cookie/datalayer
        },
        trackingCallback: function(experiment, result) {
          gtag('event', 'experiment_viewed', {
            'event_category': experiment,
            'experiment_id': experiment.key,
           'variation_id': result.variationId,
  });
}
      });

      // TODO: Instrument DOM with AB test logic
      gb.loadFeatures().then(function() {
        // NOTE: We may wish to remove `gb.loadFeatures()` and instead manually implement experiment logic
      });
    }
  })();
</script>
Here is the code I use with GTM
experimenting with gtag('event' or gtag("event" bring no results
adding this code have no effect
window.gtag = window.gtag || function() { dataLayer.push(arguments); };
h
There are a lot of things that could be going wrong; it's difficult to offer a suggestion without knowing which thing(s) are broken. You might try console.log() sprinkled throughout to see what's actually happening (or use a debugger if you prefer): • does the
index.min.js
script actually load? (check browser network tab) • does the SDK integration <script> load? • does
startGrowthbook()
actually trigger? • does the SDK get constructed? (you can check
window._growthbook
in your browser console if you add
enableDevMode: true
to your constructor) • do you have a valid experiment that would trigger the callback? • are you actually triggering the experiment via
.isOn()
or similar? I don't see anything in your snippet about this. Here's another similar thread (with no clear resolution) but outlining the console.log strategy a bit more https://growthbookusers.slack.com/archives/C01T6PKD9C3/p1692907527349029
i
@happy-autumn-40938 Hi. Sure, I understand, but according to the service instructions, everything is supposed to work correctly. 1. Yes, this script is loading correctly 2. Yes, as well. 3. How can I check it? Console said "startGrowthbook is not defined" but I see that the changes I made with the visual editor in a preview link is active, so it should work, right? 4. Console answer with "undefined" on my window._growthbook command 5. Yes, I have one for all and I see changes made with the visual editor. 6. Not sure about .isOn() . What should be changed in my GTM code?
4. window.growthbook return me with {GrowthBook: ƒ, clearCache: ƒ, configureCache: ƒ, isURLTargeted: ƒ, setPolyfills: ƒ, …} but nothing happened in term of gtag firing
Regarding other topic - I saw it, but adding some code haven`t changed the situation
Copy code
function startGrowthbook() {
      if (window.growthbook) {
      startGrowthbook();
    } else {
      setTimeout(startGrowthbook, 100);
    }
     if (!window.growthbook) return;
h
Sounds like the SDK is loading fine but no experiment assignment happens. You should be able to verify by adding a console.log inside your
trackingCallback()
(I expect nothing is consoled). I do not see any sort of experiment assignment in your code above, just the placeholder TODO:
Copy code
// TODO: Instrument DOM with AB test logic
      gb.loadFeatures().then(function() {
        // NOTE: We may wish to remove `gb.loadFeatures()` and instead manually implement experiment logic
      });
See an example of running an experiment at the bottom of this snippet: https://docs.growthbook.io/guide/google-tag-manager-and-growthbook#strategy-2-flexible-feature-flags-less-performant
Copy code
gb.loadFeatures().then(function() {
        if (gb.isOn("green-button")) {
          document.querySelector("#button-1").classList.add("green");
        }
      });
i
So I need to code all AB tests not from Growthbook account but with the GTM snippet? Can I launch tests from Growthbook panel only with no changes to code in GTM?
h
We do have a no-code visual editor for making DOM modifications (also supports simple JS injections such as page redirects). It's only available for paid accounts, although we do have a free trial available (self service within the GrowthBook app).
i
Yes, I`m paid user (currently on a free trial) so I`m using visual editor. Should I make some changes to GTM code in this case?
h
Hm, it should work out of the box; simply loading the SDK is enough. Do you have the GrowthBook dev tools Chrome extension installed? It can make debugging a bit easier: https://chrome.google.com/webstore/detail/growthbook-devtools/opemhndcehfgipokneipaafbglcecjia Is your visual experiment running or still in draft mode? Also check your SDK connection to make sure you're including visual experiments. You could also temporarily include draft experiments to help with debugging an experiment that you haven't yet launched (see screenshot).
i
Sure, I have this tool installed, but It "Unable to locate GrowthBook SDK instance." all the time (dev mode in Chrome turned on) The test is active and running Toggles are turned on production environment
h
Are you able to force the test bucket by appending a query string? Ex:
<https://www.mysite.io/?my-experiment-id=1>
i
Yes, changes I made in visual editor appear correctly with get parameter
h
I'm also noticing in your code snippet:
Copy code
attributes: {
  cid: "{{clientId}}" // TODO: Read user/device id from a cookie/datalayer
},
Are you actually using a real userId? You need this attribute to successfully randomly assign a test bucket
i
h
also make sure you have the
id
attribute selected in your experiment's Targeting rules (example screenshot using deviceId instead of id)
i
I have an id for the experiment and no targeting rules (Applied to everyone by default. )
h
Nothing obvious jumps out at me at this point. Sometimes GTM can add a layer of fragility, and occasionally a front-end framework doesn't play nicely with visual editor experiments. Are you able to force-change your id and verify you never get bucketed for the variants? Barring that, I'd probably next put my SDK into debug mode and start looking at bucket assignment console output. To do this, you can set
growthbook.debug = true
in your code right after constructing the
growthbook
SDK instance. Then all experiment assignment log output will be output to your browser console. Hopefully will give some clues as to what's going on.
i
Thanks for your help. It seems the problem can be in GTM https://developers.google.com/tag-platform/tag-manager/datalayer#how_data_layer_information_is_processed So this can be a dead-end for us and we should use recommended SDK implementation directly to avoid these problems.
@happy-autumn-40938 Hi again. We still have a problem getting anything from the tracking callback function in the launched AB test. We have installed growthbook via npm to our website according to instructions but failed to get any results despite that we have spotted changes we made through the visual editor. Everything is working fine while using isOn(), but this requires manual installation for every test, and we want to get rid of unnecessary load to our coders and launch most tests ourselves. In debugger, we have no problems there, but the callback still returns nothing. How can we get results from the running tests via callback? Is there any method we can use to force it to launch? Here is our code of tracking callback part:
Copy code
trackingCallback: (experiment, result) => {
    // TODO: Use your real analytics tracking system
    console.log("Viewed Experiment", {
      experimentId: experiment.key,
      variationId: result.key
    });
  }
});
Can you help me here?
f
Are you getting a console log message?
What are you using for event tracking? You need to replace the console.log with whatever event tracking you have
i
No, it seems tracking callback isnt working at all usually GA4, but this time get this console log for quicker debug
f
I see
Are you setting the attributes correctly and calling loadFeatures?
i
@fresh-football-47124 Yes, they are correct and calling loadFeatures