[英]How to keep track of dynamically added nodes using MutationObserver?
[英]Using mutationObserver doesn't seem to keep track of a changing table in the DOM
我正在尝试编写一个简单的chrome扩展来更改DOM中表的值。这里重要的是网页使用ajax命令来构建和更改此表的内容。(首先,没有任何内容然后单击一个链接,并使用ajax请求(没有页面重新加载),将创建一个表,然后通过单击其他链接,将修改此表。
这是我用来监听表格变化的代码:
var target = document.querySelector('#my-table');
var observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
alert('The table has appeared');
});
});
var config = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
observer.observe(target, config);
observer.disconnect();
问题是,当我按下页面中的一个链接使表格发生变化时,什么都不会发生。当我检查chrome的控制台调试我的工作时,我看到它在页面加载后立即给了我这个错误:
Uncaught NotFoundError:无法在'MutationObserver'上执行'observe':提供的节点为null
我真的迷路了,不知道该怎么办。有人有什么建议吗? ps:这是我的扩展程序的清单文件:
"manifest_version": 2,
"name": "MyExtension",
"description": "Testing the Content Script api",
"version": "1.0",
"content_scripts": [
{
"matches": ["www.myWebsite.com"],
"js": ["script.js"]
}
],
"browser_action": {
"default_icon": "icon.png"
}
}
您需要在突变后重新评估选择,依次检查每个添加的元素。
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
mutation.addedNodes.forEach(function(node) {
if (node.id == 'my-table') { // or node.getElementsByClassName(..).length or whatever
console.log('table has appeared.');
});
});
});
});
observer.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
});
效率较低但代码较短,您可以在每次突变后重新选择整个文档:
var observer = new MutationObserver(function() {
if (document.getElementById('my-table')) {
console.log('table has appeared.');
}
});
observer.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false,
});
如果您使用简单的ID选择器,它可能是高效的,因为通过id进行选择是高度优化的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.