Puppetry
Search…
Testing Shadow DOM
Shadow DOM is a new DOM feature that helps you build components. You can think of shadow DOM as a scoped subtree inside your element. polymer-project.org
Shadow DOM is a technology that unlocks such features as isolated DOM and scoped CSS. It's usually used with custom elements to isolate their DOM from the global one. Puppetry targets are relative to a DOM scope (global or local). In order to query elements inside custom elements we have go with chained targets. So we are to create a target for the host element (the custom element root) and targets for the hosted sub-elements that point to the host target.
It's much easier to explain with an example. Imagine we have a custom element foo-component, built out of a template:
1
<foo-component id="fooShadowRoot"></foo-component>
2
<template id="fooTemplate">
3
<div id="shadowLocalTarget">
4
Local Target in Shadow DOM
5
</div>
6
</template>
Copied!
We can register the component with following code:
1
document.addEventListener( "DOMContentLoaded", () => {
2
3
function registerCustomElement( elName, templateId ) {
4
globalThis.customElements.define( elName, class extends HTMLElement {
5
constructor() {
6
super();
7
this.attachShadow({ mode: "open" });
8
this.shadowRoot.appendChild( document.getElementById( templateId ).content );
9
}
10
});
11
}
12
13
registerCustomElement( "foo-component", "fooTemplate" );
14
});
Copied!
Now if we inspect the page DOM with DevTools we can find the following sub-tree:
Let's say our goal is to access a local target (#shadowLocalTarget), hosted by foo-component element (fooShadowRoot).
With DevTools you can inspect the target element and get with Copy/JS Path code like the that: document.querySelector("#fooShadowRoot").shadowRoot.querySelector("#shadowLocalTarget") If we translate it to Puppetry it actually gives us two targets: - shadow root: #fooShadowRoot - hosted element: #shadowLocalTarget, with the first target for the parent
What we have to do first is to create in Puppetry a target for foo-component (shadow root):
Defining shadow root target
Then we create a target for the hosted element
Defining hosted element target
The first one is a simple target like we are used to have in Puppetry, but the second is chained one. While building it we expand Options, set Parent target to SHADOW_FOO and Parent type to shadow host.
Chained target
As soon as the hosted element target defined (SHADOWDOM_FOO_LOCAL) we can address it as any simple target:
Addressing a chained target
Last modified 2yr ago
Copy link