Search code examples
javascriptdomhashmutation-observers

Hash of seen DOM nodes


I'd like to attach a MutationObserver to the DOM so I can see what changes. 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.

So how can I make a hash to keep track of what I've already seen? Things I've tried:

  1. WeakMap

Doesn't work because all nodes are serialized to strings before insertion. So my keys become [object Text]. Edit: I was doing seenMap[node] = true instead of 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).

  1. Using an array of seen DOM Nodes

I'm not too excited about a linear search for each DOM change.


Solution

  • There's nothing wrong with adding properties to Node Objects. JQuery does this all the time and it's very common in browser extensions. Also, I don't mean Element attributes like <img data-foo="bar"/>. I mean adding properties to the Node Objects in JS, e.g.

    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.