我正在嘗試使用 MutationObserver 來觀察 DOM 中的變化,但似乎我無法訪問“grand”-children 節點。我已經用 subtree 和 childList 值配置了觀察者。據我了解,不可能使用 MutationObserver 獲取添加的 childList 或更改的整個 DOM 樹,它所做的只是觀察更改。相反,您應該使用 getElementById。
觀察到變化后,我嘗試使用 getElementById 在 DOM 中找到相關的“父”節點,然后爬取所有子節點。雖然我仍然沒有點擊 childNodes。
我假設首先將“父”節點插入到 DOM 中,然后在事后將子節點插入到“父”節點中,盡管由于某種原因這些事件沒有在觀察者中觸發。
我懷疑我可能需要在觀察更改時更新 MutationObserver 的目標,然后繼續使用 getElementById 并爬取這些節點。
關于為什么這些 childNodes 是不可觀察的,和/或如何解決這個問題的任何想法?
最好的祝福。
MutationObserver 的代碼
function createObserver() {
const documentBody = document.body;
// callback function to execute when mutations are observed
const observer = new MutationObserver(mutationRecords => {
let addedNodes = []
for (const mut of mutationRecords) {
let arr = Array.prototype.slice.call(mut.addedNodes)
arr = arr.filter(node => popupTagNames.includes(node.tagName)); // Keep only selected tags
if (arr.length == 0) return; // don't keep empty
addedNodes = addedNodes.concat(arr)
let el = document.getElementById(addedNodes[0].id);
// Crawler
inspectNode(el)
}
})
const config = { attributes: true, childList: true, subtree: true, characterData: true }
observer.observe(documentBody, config)
}
uj5u.com熱心網友回復:
讓我們通過記錄屬于 #qc-cmp2-container 元素的添加節點來進行調查:
new MutationObserver(mutations => {
const parent = document.getElementById('qc-cmp2-container');
if (parent) console.log(...mutations.flatMap(m =>
[...m.addedNodes].filter(n => parent.contains(n)).map(n => n.cloneNode(true))));
}).observe(document, {subtree: true, childList: true});
我們將看到幾個單獨的呼叫:
- 主#qc-cmp2-container 及其空子容器
- 包含大量子元素和文本的內部 div
- 添加了兩個額外的內部元素
最節省資源的解決方案是使用超快速的getElementById檢查等待父級,然后切換到觀察父級:
function waitForId(id, callback) {
let el = document.getElementById(id);
if (el) {
callback(el);
} else {
new MutationObserver((mutations, observer) => {
el = document.getElementById(id);
if (el) {
observer.disconnect();
callback(el);
}
}).observe(document, { subtree: true, childList: true });
}
}
waitForId('qc-cmp2-container', parent => {
new MutationObserver((mutations, observer) => {
// do something
}).observe(parent, { subtree: true, childList: true });
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/452223.html
標籤:javascript dom 谷歌浏览器扩展 定时 突变观察者
