Using event attributes with custom events and GTM

Viewed 516

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?

4 Answers

Think of your problem as if a client uses the search event and has a dynamic 'search_term' parameter within the event:

  • You have your dataLayer in place

  • Your GTM is setup:

    • Variable: dataLayer variable -> DataLayerVariableName: 'instrument'
    • Trigger: customEvent -> eventName: 'make_noise'
    • Tag: GA4 Event -> eventName: 'make_noise', parameters: {{instrument from DLV}}
  • Set up Analytics under custom events (you should add 'make_noise') and custom definition (you should add 'instrument')

That should be it ...


Edit:

Custom definition of a search_term parameter

I guess all you have to do is wrap the object keys in [customKey]

I was reading your question and suddenly realized that this problem isn't specifically with Google Analytics. While of course it is about Google Analytics, the question is meant to ask, "How do I set dynamic keys in objects?" The way to do this is wrapping the dynamic key in brackets. The code below works.

gtag('event', 'make_noise', {instrument: 'gituar'})

Lets say you wanted to send a custom instrument:

let sender = prompt('Give me an instrument'); //=> Drums
gtag('event', 'make_noise', {instrument: sender})
/*
This becomes:
gtag('event', 'make_noise', {instrument: 'Drums'})
*/

TL;DR But sending a custom key would be done like so:

let customKey = prompt('Give me a key value'); //=> Fruit
gtag('event', 'make_noise', {[customKey]: 'Drums'})
/*
This becomes:
gtag('event', 'make_noise', {Fruit: 'Drums'})
*/
Related