I've followed the Google docs to add GTM tags to my site. For some reason the call back is firing 3 times, however, I only have this tag on the page.
  window.dataLayer.push({
         'event': 'add_expense',
         'eventCallback': function () {
                             alert('wtf');
                          }
         });   
Anyone have any clues on why this may be?
It could be you have multiple GTM containers on the page, including plugins. You can check to see if the callback is being passed different containers ids:
'eventCallback': function (id) {
                         alert(id);
                      }
This happened to me after enabling GA4 in the page. Seems like it is using same container and rules as GTM and caused callbacks to fire twice. My solution:
const buildGtmCallback = (callback) => {
 //GA4 is also a container, so need to fire callbacks only once, for GTM container
 //GA4 containerId starts with G-
 return (containerId) => {
    if (containerId.startsWith("GTM-") && typeof callback === "function") {
        callback();
    }
 }
}
And then whatever you wish to be fired only once:
window.dataLayer.push({
     'event': 'add_expense',
     'eventCallback': buildGtmCallback(function () {
                         alert('wtf');
                      })
     });
This solution will also work if you have multiple GTM containers by modifying containerId.startsWith("GTM-") and replace “GTM-“ with the container ID you wish the event to fire for. However in that case you won’t be sure event was fired for both containers, just that one
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With