imp*_*raw 2 javascript dom interception mutation-observers
如何创建一个观察实例MutationObserver以忽略由我的代码引起的某些 DOM 更改?例如(使用 jQuery):
//initialize MutationObserver
var mo = new MutationObserver(mutations => console.log(mutations));
mo.observe(document.body, {attributes: true, subtree: true, characterData: true, attributeOldValue: true, characterDataOldValue: true, childList: true});
//case 1: perform a removal
$('.someDiv').remove();
//in this case an action is logged by MO
//case 2: perform a removal with a disconnected MO
mo.disconnect();
$('.someDiv').remove();
mo.observe(document.body, {...});
//in this case an action is logged again!
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,MO 都会记录我对 DOM 所做的所有更改。我想出的唯一方法是:
//case 3: perform a removal with a disconnected MO, turning on after a timeout
mo.disconnect();
$('.someDiv').remove();
setTimeout(() => mo.observe(document.body, {...}), 500); //pseudo
//in this case MO skips an action above
Run Code Online (Sandbox Code Playgroud)
但这并不是该问题的最佳解决方案,因为在超时期间用户可能会在页面上引起其他一些操作,或者可以在超时之后的某个时间调用 MutationObserver 的回调。
MutationObserver 的回调是异步调用的,因此当前执行的代码所做的更改会累积并仅在完成时提交。
这就是 JavaScript事件循环的工作原理。
如果在同一个event 中断开连接并重新连接,则需要明确地耗尽队列:
mo.disconnect();
mo.takeRecords(); // deplete the queue
..............
mo.observe(......);
Run Code Online (Sandbox Code Playgroud)