简体   繁体   English

看到的DOM节点的哈希

[英]Hash of seen DOM nodes

I'd like to attach a MutationObserver to the DOM so I can see what changes. 我想将MutationObserver附加到DOM,以便可以看到发生了什么变化。 Easy. 简单。

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    processNode(mutation.target);
  });
});

var config = {
  attributes: true,
  childList: true,
  characterData: true,
  subtree: true
};
observer.observe(document.body, config);

The problem is in processNode I want to edit the nodes, which triggers the MutationObserver which calls processNode again which double edits the node, which I don't want. 问题出在processNode我想编辑节点,这会触发MutationObserver ,后者再次调用processNode ,从而对节点进行两次编辑,而这是我不想要的。

So how can I make a hash to keep track of what I've already seen? 那么,如何进行散列来跟踪已经看到的内容呢? Things I've tried: 我尝试过的事情:

  1. WeakMap WeakMap

Doesn't work because all nodes are serialized to strings before insertion. 不起作用,因为所有节点在插入之前都已序列化为字符串。 So my keys become [object Text] . 所以我的键变成[object Text] Edit : I was doing seenMap[node] = true instead of seenMap.set(node, true) . 编辑 :我在做seenMap[node] = true而不是seenMap.set(node, true) The latter works as a solution to my problem. 后者可以解决我的问题。

  1. Storing attribute on the node 在节点上存储属性

I don't want to cause collisions with anything else running on the page (I'm writing a Chrome Extension). 我不想与页面上运行的其他任何内容发生冲突(我正在编写Chrome扩展程序)。

  1. Using an array of seen DOM Nodes 使用可见的DOM节点数组

I'm not too excited about a linear search for each DOM change. 对于每个DOM更改进行线性搜索,我并不感到兴奋。

There's nothing wrong with adding properties to Node Objects. 向节点对象添加属性没有错。 JQuery does this all the time and it's very common in browser extensions. JQuery一直这样做,这在浏览器扩展中很常见。 Also, I don't mean Element attributes like <img data-foo="bar"/> . 另外,我也不是说<img data-foo="bar"/>类的Element属性。 I mean adding properties to the Node Objects in JS, eg 我的意思是向JS中的节点对象添加属性,例如

document.body.MY_WEIRD_PROP_348u9erhhhhh0asdf_IN_USE = 1

Obviously, you'd want it to be obscure to fully avoid collisions. 显然,您希望它模糊起来以完全避免碰撞。 If you can think of an instance where this would interfere with another script, please enlighten me. 如果您能想到某个实例会干扰其他脚本,请赐教。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM