Felipe César
Felipe César

Reputation: 1444

How to detect elements with shadow dom?

I'm trying to detect if an extension is installed by checking if it adds a specific div inside the body.

When the extension is installed it adds the following div in the end of the body:

<div>
  #shadow-root (closed)
    <div id="extension_name">
      <!--div content here-->
    </div>
</div>

Is there a way to detect this element with a simple document query like:

document.body.queryselector(':shadow-root #extension-name')

If not, any suggestion about an efficient way to check if this element exists?

Upvotes: 2

Views: 1761

Answers (2)

Your code:

  • doesn't detect when there are multiple/nested shadowRoots

  • doesn't detect when any of those is a closed shadowRoot

instead

  • Make you component listen at document level for a extension_name Event

  • Let your testcode dispatch a extension_name Event

You can even pass a function in event.detail and let your extension execute it

Upvotes: 0

Felipe C&#233;sar
Felipe C&#233;sar

Reputation: 1444

So looks like it's impossible to get the information when the shadow dom is closed. So I had to find alternative ways to detect the extension.

When it's open we can query using:

const isInstalled = Array.from(window.document.body.children).reverse().find(
  (item) => item.localName === 'div' && item.shadowRoot !== null && item.shadowRoot.querySelector('#extension_name')
) !== undefined;

Ps: Most of the extensions append the div on the end of the body. So reverse is intended to optimize the query.

Thanks @wOxxOm and @Louys Patrice Bessette for the help.

Upvotes: 1

Related Questions