MutationObserver监控DOM变化

MutationObserver

基于 MutationObserver 的元素属性变化监测。
The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

简言之,MutationObserver 可以监测到 DOM 元素上任何属性的变化情况,如有需要,也可以监听其子元素的变化情况。

当用户通过 devtools 修改了元素的属性时,MutationObserver 可以及时地通知我们.有一点需要注意的是,MutationObserver 监听的是元素的属性,即 attributes,所以我们的 css 样式应当作为元素的 style 属性内嵌在 HTML 中。

以下代码是本方案的具体实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// <h1 style="margin:100px;">别改我</h1>

const options = {
childList: true,
attributes: true,
subtree: true,
attributesOldValue: true,
characterData: true,
characterDataOldValue: true,
}

const reset = (expression = () => {}) => {
setTimeout(() => {
observer.disconnect();
// 执行恢复方法
expression();
observer.observe(h1, options);
}, 0);
}

const callback = (records) => {
const record = records[0];
if (record.type === 'attributes' && record.attributeName === 'style') {
reset(() => {
h1.setAttribute('style', 'margin:100px;');
});
} else if (record.type === 'characterData') {
reset(() => {
h1.textContent = '别改我'
});
}
}

const observer = new MutationObserver(callback);
observer.observe(h1, options);

禁止修改 h1 元素的 style 和 textContent,可以直接复制到 IDE 里玩一下。

这里可以直接把 style 的值抽取为一个常量,但凡用户修改了元素的 style 属性,这段代码会自动用刚才的固定常量覆盖用户修改后的值.