liveBook · Manning

attachShadow

As explained in Web Components in Action

attachShadow is a browser DOM method that attaches a shadow root to an element and returns a reference to that root.

Use attachShadow to attach a shadow root to a custom element. The method returns the root reference, which lets you populate the component even when its mode is closed. section 8.2

Create and populate an open shadow root

In connectedCallback(), call this.attachShadow({mode: 'open'}), then assign markup through this.shadowRoot.innerHTML. Open mode also exposes the root through the element’s shadowRoot property. section 8.2

Keep the returned reference in closed mode

const root = this.attachShadow({mode: 'closed'}); root.innerHTML = `<div class="inside-component">My Component</div>` A closed root makes shadowRoot null, but the return value remains usable inside the creating function. section 8.2

Closed mode limits ordinary access rather than providing real security: attachShadow can be replaced before component creation, defeating the intended isolation. section 8.2

Listing 8.2. Using the Shadow DOM in a simple component
connectedCallback() {
   this.attachShadow({mode: 'open'});                       #1
   this.shadowRoot.innerHTML =
   `<div class="inside-component">My Component</div>`       #2
}

See the minimal component example that attaches an open shadow root and writes its internal markup. section 8.2

How Web Components in Action covers it

How deep it goes
Demonstrates open and closed modes, returned references, initialization locations, and bypassable isolation.
Examples
Uses a sample component, innerHTML assignments, open and closed roots, and a prototype replacement attack.
What it assumes
Assumes familiarity with HTML elements, JavaScript classes, custom elements, and innerHTML.
What you can do after
Builds a component that creates and populates an open or closed shadow root.
How it connects
Connects attachShadow with Shadow DOM, shadow roots, Web Components, connectedCallback, constructors, and custom elements.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.