Reputation: 55
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?
Upvotes: 4
Views: 3530
Reputation: 589
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
Upvotes: 3
Reputation: 196
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);
}
Upvotes: 12