1

I'm trying to write a script that detects clicks on a button for a page the HTML of which I do not control.

However, if I add an event listener on the document, the target of the event object is an element named "c-sto_com_fs-content-page", and not my "a.btn-primary" button. In Firefox the proprietary originalTarget property does show me the right element, but that's not a great help. The "c-sto_com_fs-content-page" element is located about halfway between my button and the document body. This page's HTML is a bit of a mess.

I figured I could simply querySelector my way to the button, and hook up an event listener that way, but document.querySelector("c-sto_com_fs-content-page a.btn-primary") also returns null. document.querySelector("c-sto_com_fs-content-page") returns the custom element, but I can't use this node to navigate down. It's as if this node's children do not exist.

How do I get this working?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Menno van den Heuvel
  • 1,851
  • 13
  • 24

1 Answers1

0

The element <c-sto_com_fs-content-page></c-sto_com_fs-content-page>, is a web component on the page. The .target property of the Event object will always be the web component. Use the Event.composedPath() method to get to an element within the web component in the document's click handler.

document.addEventListener("click", (e) => {
    console.log(e.target); // Always returns <c-sto_com_fs-content-page>
    console.log(e.composed);
    console.log(e.composedPath());
});

The web component is in open mode or closed mode. See this SO post. If it's in open mode then the following should return the element within the web component that's the target of the click event.

console.log(e.composedPath()[0]);

Inspecting the HTML in the browser's console will show if the web component is in open or closed mode:

<c-sto_com_fs-content-page>
    #shadow-root (open)
    <a class="btn-primary">Ok</a>
</c-sto_com_fs-content-page>

As per the MDN article,

...the event listeners only propagate as far as the element itself, but not to the nodes inside the shadow boundary.

Here's an older post on the topic of getting the event target within a web component.

Dave B
  • 1,105
  • 11
  • 17