Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't MutationObserver code run on 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 alert because a div element is inserted to the DOM. But it appears MutationObserver codes don't run. How can I successfully make the MutationObserver code run?

like image 841
weilou Avatar asked Oct 03 '13 03:10

weilou


People also ask

What is MutationObserver?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree. It is designed as a replacement for the older Mutation Events feature, which was part of the DOM3 Events specification.

How to stop MutationObserver?

disconnect() The MutationObserver method disconnect() tells the observer to stop watching for mutations. The observer can be reused by calling its observe() method again.


1 Answers

Add subTree option as well, it should work, you want to monitor not just children of document ( head/body) but it's descendants as well. (And that is the reason when set to document.body it works).

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

Fiddle

From documentation

subtree: Set to true if mutations to not just target, but also target's descendants are to be observed.

So what you are adding is a descendant of the document not its child (or direct descendant). It is a child of body (and that is why just mentioning childList and using document.body works). You need to mention subTree if you want to monitor the changes deep.

Also see the note as well:

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

like image 120
PSL Avatar answered Sep 20 '22 12:09

PSL