Search code examples
javascriptgoogle-analyticsgoogle-tag-managergoogle-analytics-4

Listening for a JS event implemented via GTM and tracking it in GA4


My page integrates an app which provides a JS SDK.

This SDK allows me to listen for events and do callbacks like this one:

function doThis() {
    // tell GA4 the event happened
}

$myApp.push(["on", "event:triggered", doThis]); 

I've implemented GTM on my website following the updated instructions, and I am able to push the above code onto my page by using this setup:
Trigger: On Window loaded
Tag: Custom HTML (with the above code)

I've also been able to implement GA4 through GTM by creating a Tag for the GA4 Configuration with my Measurement ID (on Window Loaded as well).

However, I do not understand how the above event (which I've implemented through GTM) can be tracked in GA4.
I would like to be able to see this event the same way I am able to view page views for instance.

I imagine this is probably basic, but I've not been able to figure it out despite my attempts.


Solution

  • You're correct. This is basic indeed. All you need in your callback is to push an event to the dataLayer. Something like:

    window.dataLayer = dataLayer || [];
    dataLayer.push({event: "name-it-meaningfully"});
    

    Then in GTM, you make a trigger like so:

    enter image description here

    That's it. This trigger will be triggered by your callback. You can add more fields to that object and they will be available on the DL Event trigger.

    Read more on DL here.