Integrate Kameleoon with Google Analytics 4

portrait de l'auteur Julie Trenque

Written by Julie Trenque

Updated on 22/09/2020

2 min

Intermediate

Was this content useful?

Google Analytics 4 (GA4) is ready and fully functional from October 16, 2020.

The main difference between Universal Analytics and GA4 is that GA4 is event based. Instead of sending custom dimensions like in UA, GA4 will handle events, which can be used in the GA4 interface. Custom dimensions in GA4 could be used to handle events more easily in your reports. Also, one of the advantages of GA4 is that it can be used for any kind of property: website, mobile app, or both.

Learn more about Google Analytics 4

The Kameleoon x GA4 integration will allow to use GA4 to analyse all your campaigns by showing you which users are participating in experiments and personalizations for further analysis.

If you are still using UA, we recommend our Google Universal Analytics integration.

Requirements for GA4

  • You have implemented the gtag.js script on your website.
  • You have updated the GA4 property in Google Analytics
  • You no longer have UA analysis on the page (or you want to change that in the near future)

Enable GA4 integration on Kameleoon

On your Kameleoon account, click on “Administrate” in the left menu, then on “Sites”.

On the card of your website, click on “Configuration”: you access the configuration of your website on Kameleoon.

Unfold the “General” section.

Copy the following script and paste it into Global custom script.

// start GA4 - GTAG Integration 
(function() {
    const gtagMeasurementID = 'default' // if you want to send data to a specific Google GA4 MeasureID - use your own ID e.g. G-NDPJ085xyz 

    let setKameleoonTrackingTime = function (kameleoonTrackingTimes) {
        if(kameleoonTrackingTimes) {
            sessionStorage.setItem("kameleoonAnalyticsTrackingTimes", JSON.stringify(kameleoonTrackingTimes));
        }
    };

    let checkKameleoonTrackingTime = function (expID, trackingSolutionName, type) {
        let kameleoonTrackingTimesString = sessionStorage.getItem("kameleoonAnalyticsTrackingTimes");
        let kameleoonTrackingTimes = kameleoonTrackingTimesString == null ? {} : JSON.parse(kameleoonTrackingTimesString);
        let key = type == 'exp' ? "Experiment-" + expID : "Personalization-" + expID

        if (    null == kameleoonTrackingTimes[trackingSolutionName] ||
                null == kameleoonTrackingTimes[trackingSolutionName][key] ||
                new Date().getTime() >= kameleoonTrackingTimes[trackingSolutionName][key] + this.timeBeforeSendTracking
        ) {
            if (null == kameleoonTrackingTimes[trackingSolutionName]) {
                kameleoonTrackingTimes[trackingSolutionName] = {};
            }
            kameleoonTrackingTimes[trackingSolutionName][key] = new Date().getTime();
            return kameleoonTrackingTimes;
        }
        return false;
    };

    const processGTAGTracking = function(exp, type) {
        const eventName = (type === 'exp') ? 'Kameleoon Experiment' : 'Kameleoon Personalization';

        if (checkKameleoonTrackingTime(exp.id, 'gtagGA4', type) && ( exp.active || exp.redirectProcessed) ) {
                
            let properties = exp.id+' - '+exp.name+' - '+exp.associatedVariation.id+' - '+exp.associatedVariation.name;
                        
            Kameleoon.API.Core.runWhenConditionTrue(function(){
                return typeof gtag !== 'undefined';
            }, function(){
                if(typeof gtagMeasurementID !== 'undefined' && gtagMeasurementID !== '') {
                    gtag('event', eventName, {
                        'send_to': gtagMeasurementID,
                        'experiment_variation' : properties, 
                        'event_callback': setKameleoonTrackingTime(checkKameleoonTrackingTime(exp.id, 'gtagGA4', type)),
                        'event_timeout' : 2000
                    });
                }
            });    
        }
    } // end processGTAGTracking

    // We loop over the experiments
    Kameleoon.API.Experiments.getActive().forEach(exp => processGTAGTracking(exp,'exp'));
    window.addEventListener('Kameleoon::ExperimentActivated', function(event) {
        processGTAGTracking(event.detail.experiment, 'exp');
    });

    // We loop over the personalizations
    Kameleoon.API.Personalizations.getActive().forEach(perso => processGTAGTracking(perso,'perso'));
    window.addEventListener('Kameleoon::PersonalizationActivated', function (event) {
        processGTAGTracking(event.detail.personalization, 'perso');
    });
    
})();
// end GA4 - GTAG Integration

You can adapt the code to your needs.

For instance if you don’t have the personalization module you can remove this part of the code:

// We loop over the personalizations
Kameleoon.API.Personalizations.getActive().forEach(perso => processGTAGTracking(perso,'perso'));
window.addEventListener('Kameleoon::PersonalizationActivated', function (event) {
processGTAGTracking(event.detail.personalization, 'perso');
});

Then click on “Validate”.

This script will be loaded every time kameleoon.js is loaded (basically, each time the page is loaded).

The update will take several minutes until the global script is updated on our CDN.

Please note that the code has been optimized to only send one GA event per campaign and per visit.

Kameleoon GA4 custom definitions / custom dimensions Setup

Create custom dimensions will help to select your experiments and personalizations for GA4 segments in your GA4 reports.

Click on “Custom definitions” under “Configure” (in the left-hand menu), then click on “Create custom dimensions”.

For Kameleoon, we recommend creating these custom dimensions:

For A/B testing

  • Dimension name: Kameleoon Experiment Variation (for example)
  • Scope: Event
  • Description: contains experimentId-experimentName-associatedVariationId-associatedVariationName
  • Event parameter: experiment_variation

For Personalization

  • Dimension name: Kameleoon Personalization Variation (for example)
  • Scope: Event
  • Description: contains experimentId-experimentName-associatedVariationId-associatedVariationName
  • Event parameter: personalization_variation

That’s it! Whenever a visitor is bucketed into an experiment  or personalization campaign, Kameleoon will send the data to the defined custom dimensions.

  • In this article :