是否可以检测到DOM中的更改并使其不发生? [英] Is possible to detect a change in the DOM and make it not happen?

查看:44
本文介绍了是否可以检测到DOM中的更改并使其不发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能以某种方式监视DOM插入和对DOM的修改,然后以某种方式确定它是否完成?通过一些参数取消事件或导致事件不会在我执行自定义操作(例如一秒钟的回调)时发生.

Is it possible to somehow monitor the DOM insertions and modifications to the DOM and then decide in some way it is done or not? Through some parameter to cancel the event or cause the event does not occur while I perform a custom action, eg one second callback.

无需在所有浏览器中都可以使用,更具体地说,我需要在某些情况下应用它,并且特别是要针对我为Google Chrome创建的扩展程序(即浏览器为Google Chrome)执行测试.

No need to work in all browsers, more specifically I need it to apply in some situations and specifically'm performing tests on an extension that I'm creating for Google Chrome so the browser is Google Chrome.

DOM中有一个元素,我通过扩展对其进行了修改并在正确的位置发生,但是此DOM元素在发送" DOM元素的某个操作(发送消息)被升级"后更新,并返回到其原始状态,已删除我所做的更改,我需要始终保留更改,而不是保留通过站点修改DOM所施加的原始"更改.

There is an element in the DOM, which I modify it by extending and occurs right but this DOM element is updated after a certain action (send message) to send the DOM element is "upgraded" and returns to its original state removing the changes I made, what I need is to always keep my changes and not the "original" that is imposed by modifying the DOM through the site.

推荐答案

注意更改:

您正在寻找的是 MutationObserver .

来自 MDN

// select the target node
var target = document.querySelector('#some-id');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
  });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

它们在最新版本的Chrome浏览器上工作,因此,在扩展名.

They work on recent versionf of Chrome so you shouldn't have any problem using them in an extension.

关于回滚,我怀疑您必须自己回滚.

As for rolling it back, I suspect you'd have to roll it back yourself.

这是一种回滚策略:

  1. 使用 Node克隆正在观看的节点.cloneNode(true) (该参数表示深度克隆)
  2. 用变异观察者观察节点.
  3. 致电 Node.replaceChild 更改时从其父项开始.

虽然这不是最有效的方法,但它是最简单的方法,而且实施起来也很简单.一种更激烈但又可能更快的方法是使用返回的突变数组自己还原每个突变.

While this is not the most efficient approach it is the simplest and is simple enough to implement. A more drastic but perhaps faster approach would be reverting every mutation yourself using the returned mutation array.

如果只想防止其他代码接触它,则有一种更简单的方法.

If you just want to prevent other code from touching it, there is a simpler way.

  1. 使用 Node.cloneNode(true) (该参数表示深度克隆).
  2. 等待,直到确定调用它的外部代码已获得对它的引用.
  3. 致电 Node.replaceChild 从其父级开始,外部代码现在正在保存对不在文档中的节点的引用,并且更改不会反映在演示文稿中.
  4. 此外,您可能想要更改其ID,类名和其他标识"信息,因此,如果外部代码从DOM中懒惰地选择它,则外部代码将无法捕获它.

这篇关于是否可以检测到DOM中的更改并使其不发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆