Why doesn't MutationObserver code work in Chrome 30?

From http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers I got the following code:

var insertedNodes = []; var observer = new WebKitMutationObserver(function(mutations) { alert('run'); mutations.forEach(function(mutation) { for (var i = 0; i < mutation.addedNodes.length; i++) insertedNodes.push(mutation.addedNodes[i]); }) }); observer.observe(document, { childList: true }); console.log(insertedNodes); var divElement = document.createElement('div'); divElement.innerHTML = 'div element'; document.querySelector('body').appendChild(divElement); 

jsFiddle: http://jsfiddle.net/cUNH9

As you can see, we should see a warning because the div element is inserted into the DOM. But it looks like MutationObserver codes are not starting. How can I successfully execute the MutationObserver code?

+8
javascript html5 mutation-observers mutation-events mutation
source share
1 answer

Add the subTree parameter, it should work, you want to control not only the children of the document ( head/body ), but also the descendants. (And that is the reason when it is set to document.body , it works).

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

Fiddle

From the documentation

subtree: set to true if mutations are not intended for the target, but target descendants must also be specified.

So what you add is a descendant of document , not its descendant (or direct descendant). This is a child of the body (and therefore just mentioning childList and using document.body works). You must specify subTree if you want to deeply track changes.

Also note the note:

NOTE. At the very least, childList, attributes, or characterData must be set to true. Otherwise, "An invalid or invalid string was specified" an error is thrown.

+12
source share

All Articles