Use DataLayer Variables in Experiments
Overview
DataLayer variables can be used as an alternative to Customer Attributes. This is useful when you have a dataLayer variable that gets populated as soon as a visitor lands on your page, and you want to use that value inside your experiment.
Example: when a visitor lands on the Sign Up page, show the text "Sign up today for #{{Company name}}", pulling the company name from a dataLayer variable.
This is done using custom code inside your experiment's Variation.
Implementation
Create or open your A/B Testing or Personalization experiment, add a new Variation from the Variations tab, and press the </> Code button.
You'll need to know the exact details of the dataLayer variable you're reading before implementing the code.
Option 1 - Reading the raw dataLayer array
function checkDataLayer() {
const data = window['dataLayer'];
for (let i = 0; i < data.length; i++) {
const dataItem = data[i];
const isNameEvent = dataItem.event === 'company_name_event';
if (isNameEvent) {
const companyName = dataItem.value;
makeExperimentChanges(companyName);
return;
}
}
}
function makeExperimentChanges(companyName) {
const targetElementSelector = 'button';
const targetElement = document.querySelector(targetElementSelector);
if (!targetElement) {
return;
}
const updatedText = `Sign up today for ${companyName}`;
targetElement.textContent = updatedText;
}
checkDataLayer();
This code runs specifically for that variation: it checks the dataLayer, and once it finds the desired event containing the company name, takes the value and applies the experiment change.
This is a demonstration example. You'll need to adjust:
-
The event name checked inside
checkDataLayer()to match your actual dataLayer event. -
targetElementSelectorinmakeExperimentChanges()to a CSS selector for the element you want to change.
If you want to insert a new element instead of modifying an existing one, makeExperimentChanges() will need further changes accordingly.
Option 2 - A simpler approach via the GTM dataLayer API
function checkDataLayer() {
const gtmID = 'GTM-XXXXXX';
const propName = 'company_name';
if (typeof window.google_tag_manager === 'object') {
const companyName = google_tag_manager[gtmID].dataLayer.get(propName);
if (companyName) {
makeExperimentChanges(companyName);
}
}
}
Replace gtmID and propName with your actual GTM container ID and dataLayer property name.