影子dom-知道何时渲染/更改dom [英] shadow dom - know when dom is rendered/changed
本文介绍了影子dom-知道何时渲染/更改dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个Chrome扩展程序,该扩展程序可以在页面加载或更改时修改元素的属性.
我使用Mutation Observer进行此操作.但是,在加载/更改shadow-dom(即嵌入式Twitter帖子)时,不会调用观察者的处理程序.
是否有一种方法可以在加载/更改shadow-dom时获取事件,或将突变观察者挂钩到该事件?
谢谢!
解决方案
您可以简单地 observe()
具有Shadow DOM的元素的 shadowRoot
属性.>
customElements.define('image-list',classextended HTMLElement {connectedCallback(){var观察者=新的MutationObserver(function(mutations){变异.forEach(函数(变异){//检测< img>插入如果(mutation.addedNodes.length)console.info('节点已添加:',mutation.addedNodes [0])})})this.attachShadow({mode:'open'}).innerHTML ='< img alt =图片1">'rator.observe(this.shadowRoot,{childList:true})}添加图片() {var img = document.createElement('img')img.alt ='新图片'this.shadowRoot.appendChild(img)}})
< image-list id = LI></image-list>< button onclick ="LI.addImage()">添加图像</button>
I am writing a chrome extension that modifies elements properties as a page is loaded or changes.
I do this using a Mutation Observer. However the observer's handler is not called when shadow-dom (ie, embedded twitter posts) are loaded/changed.
Is there a way to get an event when shadow-dom is loaded/changes or to hook a mutation observer to it ?
Thanks!
解决方案
You can simply observe()
the shadowRoot
property of the element with a Shadow DOM.
customElements.define('image-list', class extends HTMLElement {
connectedCallback() {
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//Detect <img> insertion
if (mutation.addedNodes.length)
console.info('Node added: ', mutation.addedNodes[0])
})
})
this.attachShadow({mode: 'open'}).innerHTML = '<img alt="image 1">'
observer.observe(this.shadowRoot, {childList: true})
}
addImage() {
var img = document.createElement('img')
img.alt = ' new image '
this.shadowRoot.appendChild(img)
}
})
<image-list id=LI>
</image-list>
<button onclick="LI.addImage()">Add image</button>
这篇关于影子dom-知道何时渲染/更改dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文