[英]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.我试图通过检查是否在正文中添加了特定的 div 来检测是否安装了扩展。
When the extension is installed it adds the following div in the end of the body:安装扩展后,它会在正文末尾添加以下 div:
<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?如果没有,关于检查此元素是否存在的有效方法的任何建议?
So looks like it's impossible to get the information when the shadow dom is closed.因此,当影子 dom 关闭时,似乎无法获取信息。 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. ps:大部分扩展append div放在body尾部。 So
reverse
is intended to optimize the query.所以
reverse
旨在优化查询。
Thanks @wOxxOm and @Louys Patrice Bessette for the help.感谢@wOxxOm 和@Louys Patrice Bessette 的帮助。
Your code:你的代码:
doesn't detect when there are multiple/nested shadowRoots不检测何时有多个/嵌套的 shadowRoots
doesn't detect when any of those is a closed
shadowRoot没有检测到其中任何一个是
closed
的 shadowRoot
instead反而
Make you component listen at document
level for a extension_name
Event让您的组件在
document
级别监听extension_name
事件
Let your testcode dispatch a extension_name
Event让您的测试代码分派一个
extension_name
事件
You can even pass a function in event.detail
and let your extension execute it您甚至可以在 event.detail 中传递一个
event.detail
并让您的扩展程序执行它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.