trusktr trusktr - 1 year ago 62
HTML Question

How do we detect if a shadow root was made with v0 or v1 API?

Suppose a JS module exports

which was created with either
(we don't know which). How do we detect if the root is a v0 shadow root or a v1 shadow root (i.e. how do we detect which method was used to create the root)?

f.e., What would I fill in the following conditional statements?

// for argument's sake, we don't create the root, we only get a reference
// to it:
import shadowRoot from 'somewhere'

function getShadowRootVersion(root) {
if ( ... )
return 'v0'

if ( ... )
return 'v1'

console.log(getShadowRootVersion(shadowRoot)) // should output "v0" or "v1".

More info:

We want to find out if a shadow root was created from
or from
. The resulting roots are different: in the root created with
elements are used for distributing elements. In roots created with
elements don't do anything, and
elements are used instead. How do we detect which method was used to create a root (i.e. whether we have a v0 root or a v1 root)?

Answer Source

The following hack should work:

function isV1(shadowRoot) {
  const slot = document.createElement('slot');
  const assignedNodes = slot.assignedNodes({ flatten: true });
  return assignedNodes.length == 0;

IMO, there is something wrong when you have to detect it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download