I would like to prevent website wait a time to trigger all script in GTM tags.
My website have an event that will redirect to new URL when I click a button. I want to catch this event in GTM tag and add some script code to track behavior. I have setup a tag for this, it's fired correctly but sometime no event capture; I was checked and put my code to console tab and it also worked.
I want wait a sec to run my code. But don't know how to, I have tried use eventlistener('id-button') but this make conflict with default event.
I'm just add tracking in GTM and don't have access to based website code. The website also push missing datalayer. Sample below:
dataLayer.push({
event: "gtm.click",
gtm.element: "HTMLButtonElement: html > body > div.container > div.productPage1 > div.product_t" +
"op > div.pure-g > div.pure-u-1.pure-u-md-1-2 > div.product__content > div.pure-g " +
"> div.pure-u-1.pure-u-md-3-4 > div.action > button.and_checkout.btn_order.btn_add" +
"_to_cart.buy-now.preorder",
gtm.elementClasses: "and_checkout btn_order btn_add_to_cart buy-now preorder",
gtm.elementId: "",
gtm.elementTarget: "",
gtm.triggers: "10,11,12,13,14,15,16,17,18,19,20",
gtm.elementUrl: "",
gtm.uniqueEventId: 22
})
I only can adjust in GTM tag.
Update: I use beforeunload for this scenario
window.addEventListener('beforeunload', function(e) {
});
Delaying user experience for tracking purposes is a bad practice.
Look into the Beacon API. It was created exactly for these cases. I believe GA4's own gtag.js uses it by default, which means that either you introduce additional asyncness in GTM, so GTM can't initiate the network call before the page unloads, or you're just not preserving log in the Network tab to see beacons being sent.
You still can delay the page unload, of course. By overriding your CTA's default behavior and introducing a delay before triggering the navigation manually.
Also, you generally don't want to use the onbeforeunload callback for tracking. There are almost always better options.