简体   繁体   中英

MutationObserver callback doesn't fire for EMBED nodes

For some reason, the following code snippet just logs "false" 1000+ times, but never "true". I can't figure out why, because it seems to work for any other element.

// create an observer instance
// log whether the mutation is made to an EMBED node
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.dir(mutation.target.nodeName == 'EMBED');
  });
});

// configuration of the observer:
var config = {
  attributes: true, // required
  childList: true, // required
  characterData: true, // required
  subtree: true // get updates from the descendants, not just the children
};

// start observing immediately
// this works because "document" always exists
observer.observe(document, config);

I'm testing the code on this page, in the latest Opera:

https://www.facebook.com/ccstandup/videos/vb.331786510170444/1177307595618327/

(If you use the latest Opera, it should be a Flash video implemented with EMBED, but in other browsers it could be VIDEO.)

Any ideas what I'm doing wrong?

target is the element that has had a change happen to it. When an element is inserted, it isn't that element that changes, but its parent. Checking mutation.target.nodeName == 'EMBED' will check if attributes , childList or characterData of the embed element had changed, which they haven't. If you need to see when the embed element itself is inserted, you need to look at it from the point of the of a parent element, eg

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.type !== 'childList') return;

    mutations.addedNodes.forEach(function(node){
      if (node.nodeType !== Node.ELEMENT_NODE) return;

      var embed = node.tagName.toLowerCase() === 'embed' ? node :
          node.querySelector('embed');

      // Found an embed element.
      if (embed) console.log(embed);
    });
    console.dir(mutation.target.nodeName == 'EMBED');
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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