|
| 1 | +export const addCustomClickEventListener = (eventName: string) => { |
| 2 | + // Set to false if you want to track all events and not just those in shadow DOM |
| 3 | + const trackOnlyShadowDom = true |
| 4 | + |
| 5 | + const callback = function (event: MouseEvent) { |
| 6 | + if ('composed' in event && typeof event.composedPath === 'function') { |
| 7 | + // Get the path of elements the event climbed through, e.g. |
| 8 | + // [span, div, div, section, body] |
| 9 | + const path = event.composedPath() as (HTMLElement & HTMLAnchorElement & HTMLFormElement)[] |
| 10 | + |
| 11 | + // Fetch reference to the element that was actually clicked |
| 12 | + const targetElement = path[0] |
| 13 | + |
| 14 | + // Check if the element is WITHIN the shadow DOM (ignoring the root) |
| 15 | + const shadowFound = path.length |
| 16 | + ? path.filter(function (i) { |
| 17 | + return !targetElement.shadowRoot && !!i.shadowRoot |
| 18 | + }).length > 0 |
| 19 | + : false |
| 20 | + |
| 21 | + // If only shadow DOM events should be tracked and the element is not within one, return |
| 22 | + if (trackOnlyShadowDom && !shadowFound) return // Push to dataLayer |
| 23 | + |
| 24 | + if (!window.dataLayer) { |
| 25 | + window.dataLayer = [] |
| 26 | + } |
| 27 | + |
| 28 | + window.dataLayer.push({ |
| 29 | + event: eventName, |
| 30 | + custom_event: { |
| 31 | + element: targetElement, |
| 32 | + elementId: targetElement.id || '', |
| 33 | + elementClasses: targetElement.className || '', |
| 34 | + elementUrl: targetElement.href || targetElement.action || '', |
| 35 | + elementTarget: targetElement.target || '', |
| 36 | + originalEvent: event, |
| 37 | + inShadowDom: shadowFound, |
| 38 | + }, |
| 39 | + }) |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + document.addEventListener('click', callback) |
| 44 | +} |
0 commit comments