DataLayer variables can be used as an alternative to Customer Attributes.
This can be helpful in scenarios where you have a DataLayer variable which is getting populated when a Visitor lands on your page and you want to use it. For example:
When the user visits Sign up page on our website, I want to show the text “Sign up today for {{Company name}}”.
This can be done with custom code within the experiment, for the Variation.
Integration
Create or access your A/B Testing or Personalization experiment, add a new Variation from the Variations tab and press on the </> Code button.

In order to implement the custom code, the first thing that is required is to know the details of the DataLayer variable.
Option 1. Then, code like this may be inserted in the aforementioned variation’s JS:
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();
}
const updatedText = `Sign up today for ${companyName}`;
targetElement.textContent = updatedText;
}This is essentially JS code that runs specifically for that variation, checks the DataLayer, and once it finds the desired event with the company name, takes the value from it and makes the experiment changes.
Note that this is for demonstration purposes, the actual event details should be changed in the checkDataLayer function along with the targetElementSelector value in the makeExperimentChanges function (this should be a CSS selector for the desired element to be changed with the new text). If it should be a new element instead of changing an already existing one, this function should be changed further, of course.
Option 2. Alternatively, for a simpler checkDataLayer function, this could be used instead:
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);
}
}
}Important: Please note to change gtmID and propName to what is desired.