Skip to content

Commit 38d1e6d

Browse files
author
Paulo Júnior
authored
feat: add custom event listener for elements in shadow dom
1 parent b8fbdf5 commit 38d1e6d

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/index.tsx

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import App from 'App'
2+
import { addCustomClickEventListener } from 'utils/addCustomEventListener'
23
import registerCustomElement from 'utils/register-custom-element'
34

45
registerCustomElement({
56
name: 'header-app',
67
component: App,
78
})
9+
10+
addCustomClickEventListener('custom_click_event')

src/types/global.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
interface Window {
2+
dataLayer?: Record<string, unknown>[]
3+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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

Comments
 (0)