---
title: "Shadow DOM"
section: "Web Pentesting"
sectionSlug: "pentesting-web"
sourcePath: "src/pentesting-web/xss-cross-site-scripting/shadow-dom.md"
sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/pentesting-web/xss-cross-site-scripting/shadow-dom.md"
sha: "188de82beb54e70956b2952367a0af91d26758b8"
isIndex: false
modified: true
license: "CC-BY-NC-4.0"
---
# Shadow DOM
Shadow DOM encapsulates DOM and CSS implementation details, but **it is not a security boundary** for script already executing in the same origin/realm. It creates useful assessment surfaces when applications mix **closed roots**, **Declarative Shadow DOM (DSD)**, and HTML parsing/sanitizing APIs.[[3]](#references)
## Why attackers care
- `mode: "closed"` only hides the root from `element.shadowRoot`; code running in the same JS realm can still intercept its creation.[[1]](#references)
- DSD allows HTML such as `...` to create real shadow roots during parsing.
- Newer sinks such as `Element.setHTMLUnsafe()` and `ShadowRoot.setHTMLUnsafe()` can materialize DSD from attacker-controlled HTML.
- Some sanitizers still treat ``/DSD as inert markup and become bypassable when they return **live DOM** instead of a serialized string.
## Enumerating shadow roots
Open roots are trivial to enumerate:
```javascript
for (const el of document.querySelectorAll('*')) {
if (el.shadowRoot) console.log('shadow host:', el, el.shadowRoot);
}
```
When testing large applications, recursively walk every discovered `shadowRoot` because Web Components are often nested several levels deep.
## Intercepting `closed` roots
If you can run JavaScript **before** the component is initialized, hook `attachShadow()` and keep the returned reference:
```javascript
(() => {
const orig = Element.prototype.attachShadow;
window.__shadowRoots = [];
Element.prototype.attachShadow = function (init) {
const root = orig.call(this, init);
window.__shadowRoots.push({ host: this, mode: init.mode, root });
return root;
};
})();
```
This is one of the most important takeaways when auditing apps or browser extensions that wrongly assume `closed` protects secrets, CSRF tokens, anti-clickjacking UI, or privileged controls.
## Declarative Shadow DOM as an injection surface
DSD creates a shadow root directly from markup:
```html
```
Important parsing behavior for exploitation:[[2]](#references)[[4]](#references)
- `innerHTML` **does not** create declarative shadow roots.
- `Element.setHTMLUnsafe()` / `ShadowRoot.setHTMLUnsafe()` **do** parse them.
- Server-rendered HTML also creates DSD during the normal page parse.
Therefore, look for applications that:
- hydrate server-rendered components,
- import remote HTML snippets into custom elements,
- expose preview/render features backed by `setHTMLUnsafe()`, or
- wrap parsing APIs in custom “safe HTML” helpers.
Also remember that classic `