Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Tag Manager callback

I have received some dataLayer definitions to place on a website. Most of them concern clicking e.g. on main menu links. But I see the following problem:

  • I do the dataLayer.push(some data...)
  • then GTM invokes AJAX hits to the connected services, like Google Analytics
  • but then the page reloads (this is not a SPA like angularjs site) to the new location and those hits are (in my opinion) aborted - no data is saved

I was googling some solutions but it seems that no one had such an issue - quite strange, it looks like a basic problem. Maybe GTA handles it automatically and I don't have to think about this?

Thanks for help.

like image 454
saq Avatar asked Sep 26 '22 04:09

saq


1 Answers

GTM does not invoke AJAX (unless you put Ajax calls in custom HTML tags).

Google Analytics takes all configured tags, triggers and variables and wraps them into a huge javascript file. This file is loaded into your page and evaluated in the context of your page. If a trigger matches the respective tags are inserted into the DOM of the page. By that time there is no big difference between tags from GTM and tags that are coded into the source code of the page.

And like with hardcoded tags it does happen that hits are aborted when a page reloads. That's why GTM has a feature called "event callback", where you can pass a function that is executed only after all tags that are triggered by the event have been fired. Look at this example from the Google Analytics Enhanced E-Commerce Documentation:

function(productObj) {
  dataLayer.push({
    'event': 'productClick',
    'ecommerce': {
      'click': {
        'actionField': {'list': 'Search Results'},      // Optional list property.
        'products': [{
          'name': productObj.name,                      // Name or ID is required.
          'id': productObj.id,
          'price': productObj.price,
          'brand': productObj.brand,
          'category': productObj.cat,
          'variant': productObj.variant,
          'position': productObj.position
         }]
       }
     },
     'eventCallback': function() {
       document.location = productObj.url
     }
  });

Here the event callback is a function that redirects to another Url only after the tags all have been fired.

It might be wort mentioning that Google Analytics tries to avoid data loss by sending hits via the sendBeacon API (if applicable), which does not have to wait for a server response, so hits will go through even if the user navigates away from the page (however sendBeacon is not available on IE/Edge).

like image 176
Eike Pierstorff Avatar answered Oct 11 '22 04:10

Eike Pierstorff