ComposedPath Finds The Real Event Target

Listeners outside a shadow root only see the host as event.target; composedPath() returns the real inner chain, truncated to the host for closed roots.

JavascriptSecurity Boundaries

Code

snippet
// Shadow DOM retargeting: listeners outside the shadow root see the host as event.target
const host = document.createElement('user-card');
const shadow = host.attachShadow({ mode: 'open' });
const button = document.createElement('button');
button.textContent = 'Save';
shadow.append(button);
document.body.append(host);

host.addEventListener('click', (event) => {
  // From outside, event.target is the host element
  console.log('target:', event.target.tagName);
  // composedPath() hands back the real inner chain
  console.log('real target:', event.composedPath()[0].tagName);
  console.log('path length:', event.composedPath().length);
});

button.click();

// mode:'closed' truncates the path for outsiders: the first node is the host itself
const closedHost = document.createElement('closed-card');
const closedShadow = closedHost.attachShadow({ mode: 'closed' });
const inner = document.createElement('button');
closedShadow.append(inner);
document.body.append(closedHost);

closedHost.addEventListener('click', (event) => {
  console.log('closed first node:', event.composedPath()[0].tagName);
});

inner.click();

What the demo retargets

A click on the button inside an open shadow root reaches a listener on the host with event.target reported as the host, because retargeting hides inner nodes from outside observers. composedPath()[0] returns the button itself, the real first node of the propagation path.

The second half attaches a closed shadow root: composedPath still answers, but the path is truncated at the boundary, so the printed first node is the closed-card host and inner elements never appear to outsiders.

Points to remember

  • Retargeting applies to any listener outside the shadow tree.
  • closed mode cannot be escaped: even composedPath respects the boundary.

Interactive Tools for This Topic

FAQ

What does composedPath return for a closed shadow root?
A path truncated at the host: the demo prints the closed-card host as the first node, with no inner elements exposed to the outside listener.