Insights

How to launch experiments in GrowthBook based on a datalayer event

Foto van Rudger de Groot
Rudger de Groot
Founder & CRO

Share

The other day, I got a comment from another CRO that with GrowthBook, it wasn’t possible to launch experiments based on events that are pushed on the datalayer. This got me thinking… First, that’s a nice way to start an experiment because the logic is already built on the site. And by listening to events, you are piggybacking on that existing logic. Saving you time from writing/testing that targeting code yourself.

Secondly, it’s relatively easy for non-technical people to set up an experiment as long as they know the name of the event, and because there probably already is an extensive analytics implementation, there should be quite a few events to choose from, which increases the possibilities of different experiments.

Finally, it is possible to do this with GrowthBook as long as you know what code you need to add that retrieves the event’s name and sets it as a targeting attribute that GrowthBook can work with.

Luckily, I work with an awesome frontender called Pascal Louwes, and after a little back and forth, he knew enough to drum up a bit of code.

Here is a PoC for you to play around with. It’s just ment to explain the concept on how we would implement this targeting technique.

				
					// assuming there is a GrowthBook instance called growthBook.
// make sure the attribute "dataLayerEvent" is set up as
// a string[] attribute
const oldPush = window.dataLayer.push;
// overrides Google Analytics dataLayer push
// to update GrowthBook "dataLayerEvent" attribute
window.dataLayer.push = function ({
	event,
	exp_id,
	exp_var
}) {
	const states = [].slice.call(arguments, 0);
	const currentAttributes = growthBook.getAttributes();
	(currentAttributes["dataLayerEvent"] = currentAttributes["dataLayerEvent"] || []).push(event);
	growthBook.setAttributes(currentAttributes);
	return oldPush.apply(window.dataLayer, states);
};
				
			

The technique Pascal used is based on an already existing technique which is explained in this blog post by Simo

We assist companies
scaling experimentation

Our GrowthBook expert

Rudger de Groot

Founder & CEO

Contact form

Discover how we’ve helped leading brands transform their digital experiences through experimentation and innovative GrowthBook solutions.

Direct contact

Nijverheidstraat 11-1E
7511 JM Enschede
the Nederlands

+31 53 234 0444