Skip to content

Expose shadowRoot on element internals #871

@JanMiksovsky

Description

@JanMiksovsky

During the March 2020 web components virtual F2F, we discussed the fact that an element with a closed shadow root has no standard way to refer to its own shadow root:

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "closed" });
  }

  connectedCallback() {
    // Other callbacks/methods can't access shadow.
    this.shadowRoot.innerHTML = "Hello"; // Throws: Can't set innerHTML of null
  }
}

Because of this, any component that creates a closed root must maintain its own private reference to the root.

Additionally, the possibility of declarative Shadow DOM introduces a scenario in which a rehydrated component may need access to a shadow root that was automatically created for it.

For these reasons, it seems worthwhile to expose shadowRoot on an element's internals:

class MyElement extends HTMLElement {
  #internals;

  constructor() {
    super();
    this.attachShadow({ mode: "closed" });
    this.#internals = this.attachInternals();
  }

  connectedCallback() {
    // Other callbacks/methods can access shadow via internals.
    this.#internals.shadowRoot.innerHTML = "Hello";
  }
}

As before, the component must still maintain a private reference (to internals instead of the shadow root), but at least now:

  • A component that wants to have both a closed shadow root and internals has to track only a reference to the internals. Through that, it can always obtain a reference to the shadowRoot.
  • A component with declarative Shadow DOM could invoke attachInternals and then inspect the internals to determine whether a shadow root has already been created.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions