问题描述
我正在尝试使用MutationObserver
检查页面上的每个突变。
是否有一种简单的方法可以解决以下问题,因此不必将它作为内嵌脚本包含在正文中(即,将其包含在<head>
中)?
问题在于我需要bodyList
变量才能开始监视添加到页面的项目。
很明显,我不能使用onLoad事件或其他任何东西,因为到那时所有的突变都已经发生了(除非在我不知道的事实之后有某种方法可以访问它们?)。
还是有办法将变异观察者附加到文档本身而不是元素?
我确信答案很简单,但是找不到涵盖此内容的任何文档。
<body>
<script>
//I want to move this inline script into the <head>
var bodyList = document.querySelector("body"),observer = new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
console.log("MUTATION",mutation)
});
});
observer.observe(bodyList,{childList: true,subtree: true});
</script>
....all the HTML elements that I want to monitor
解决方法
您可以将观察者附加到HTML文档本身,等待<body>
出现,然后将观察者附加到正文:
// In the <head>:
new MutationObserver((_,observer) => {
const { body } = document;
if (!body) return;
// Remove this observer,since it's not needed anymore; body exists
observer.disconnect();
new MutationObserver(function (mutations) {
mutations.forEach(function (mutation) {
console.log("MUTATION",mutation)
});
})
.observe(body,{ childList: true,subtree: true });
})
.observe(document.documentElement,{ childList: true });