Firefox下Greasemonkey中如何获取更新后的DOM/文档?
问题描述
我尝试打印document对象,但返回的是旧文档而非更新后的版本。请问在子节点添加完成后,如何获取更新后的document?
const targetNode = document.getElementById('randomNode'); const config = { attributes: true, childList: true, subtree: true }; const callback = async function(mutationList, observer) { for (const mutation of mutationList) { if (mutation.type === 'childList') { console.log('A child node has been added or removed.'); await delay(2000); console.log(document) // <== 此处打印的是旧文档? } else if (mutation.type === 'attributes') { console.log(`The ${mutation.attributeName} attribute was modified.`); } } };
解决方案
首先澄清:
document对象本身始终指向当前最新的DOM树,你看到的“旧版本”是浏览器控制台的延迟求值特性导致的——控制台打印对象时不会立即序列化所有属性,而是在你点击展开时才读取当前状态,这就造成了“打印的是旧版本”的错觉。要捕获打印瞬间的DOM状态,直接打印DOM的HTML序列化内容即可,这样能看到更新后的完整结构:
console.log(document.documentElement.outerHTML);若要查看
document对象的实时属性,改用console.dir(document),它会更直观地展示DOM对象的当前属性,但仍需注意控制台的延迟显示逻辑。额外提示:代码中的
await delay(2000)完全多余,MutationObserver的回调会在DOM变更完成后立即触发,此时子节点已经成功添加到DOM树中,无需额外等待。
内容的提问来源于stack exchange,提问作者user223212
相关产品推荐
相关产品推荐

