Issues with the Google Tag Manager built into the Click and shadow-dom trigger

Google Tag Manager (GTM) has a built-in Click trigger that allows you to run GTM tags when a user clicks on things.

I suppose this does this by adding a 'click' listener to the document, and then clicking on the special event "gtm.click" in the dataLayer when creating the clicks.

The 'gtm.click' object, which is placed in the GTL dataLayer, has certain data pulled from the event.target property, including the attributes of the target element, such as id / class / href.

Problem...

If you use shadow-dom in your html, the target / data will be wrong. This is because when events bubble across the borders of the shadow domain, they are "redirected so that they look like they came from a component, not the internal elements in your shadow DOM . "

This can be problematic if you create tags / triggers / variables in GTM based on the event target data, and you expect this target to be the element the user clicks on (which seems normal).

Is there a solution for this that already exists?

+4
source share
1 answer

Ideally, GTM will fix this internally; until then, here is the solution I came up with ...

( GTM) , , ( ).

, 'click' , event.composedPath()[0] , . , , , .

function getOriginalTarget(ev) {
  if ('composedPath' in ev) return ev.composedPath()[0]; // Standard
  else if ('path' in ev) return ev.path[0]; // Old Chrome
  else if ('originalTarget' in ev) return ev.originalTarget; // Firefox
  else if ('srcElement' in ev) return ev.srcElement; // Old IE & Safari
  else return ev.target; // Fallback to normal target.
};

document.addEventListener('click', function (ev) {
  var target = getOriginalTarget(ev);

  dataLayer.push({
    'event': 'MyClick', // some custom event
    'targetId: target.id || '' // some custom data (from original target)
    // etc...
  });
}, false);

GTM 'event': 'gtm.click', , , , .. hacky, , , -, , . , GTM, 'gtm.elementClasses': target.className || '', 'gtm.elementId': target.id || '', 'gtm.elementTarget': target.target || '', 'gtm.elementUrl': target.href || target.action || '' ..

+2

Source: https://habr.com/ru/post/1686830/


All Articles