Tuesday 9 March 2021

Using event attributes with custom events and GTM

I have a problem with sending custom events to GA4 using GTM. The problem is the event attributes are dynamically pushed using dataLayer. I can't seem to find a way to reliably forward the attributes to GA4.

So we have a bit of javascript code that runs gtag('event', 'make_noise', {instrument: 'gituar'}).

Then we have a GTM tag "Google Analytics: GA4 Event" that is triggered by "make_noise" custom event above. Now, this works - we can see "make_noise" event being forwarded to our GA4 property.

What I can't figure out is how to forward the "instrument" attribute from the custom event down to GA4. I can't just add instrument: guitar attribute to the GTM tag, as the value of instrument attribute is dynamic. It can be called with wide variety of values, so I should really be able to use whatever is sent via javascript code and forward that to GA4.

So I created a "Data Layer Variable" that reads "dataModel.instrument" and I used this variable in my GA4 Event tag. It worked (dynamic "instrument" attribute is forwarded as expected), but, when I send two events in short timespan, e.g.:

gtag('event', 'make_noise', {instrument: 'gituar'});
gtag('event', 'do_stuff', {foo: 'bar'});

the "make_noise" event on the GA4 side no longer has the "instrument" attribute. It's undefined. Presumably because variable reads last state of dataModel (where only "foo" is defined).

How do I solve this?



from Using event attributes with custom events and GTM

No comments:

Post a Comment