composedPath Sees Through Shadow DOM

Read event.composedPath to recover the real shadow-DOM propagation path when retargeting makes event.target report the host element instead.

TypescriptData Integrity

Code

typescriptsnippet
22 lines
// Inside a shadow tree, listeners see real targets; from outside, the event
// is retargeted to the host. composedPath restores the propagation path.
class SavePanel extends HTMLElement {
  constructor() {
    super();
    const root = this.attachShadow({ mode: 'open' });
    root.innerHTML = '<button data-action="save">Save</button>';
  }
}
customElements.define('save-panel', SavePanel);
document.body.insertAdjacentHTML('beforeend', '<save-panel></save-panel>');

document.addEventListener('click', (event) => {
  console.log('target seen outside:', (event.target as HTMLElement).tagName);

  const trigger = event
    .composedPath()
    .find((node): node is HTMLElement =>
      node instanceof HTMLElement && node.dataset['action'] !== undefined);
  console.log('action from path:', trigger?.dataset['action'] ?? 'none');
});
// closed shadow roots filter this path for listeners outside the component

How this snippet works

composedPath Sees Through Shadow DOM comes down to the class SavePanel.

Caveats

  • Nothing is imported beyond what the runtime already provides.
  • This is browser-side code — document will not resolve in Node.

Applying it

Look for the target seen outside:, action from path: prefixes in the file’s output; they match each line up with its step.

Statements that matter

.find((node): node is HTMLElement =>
  node instanceof HTMLElement && node.dataset['action'] !== undefined);

Interactive Tools for This Topic

FAQ

Does composedPath Sees Through Shadow DOM run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.