MutationObserver回调不会为EMBED节点触发

MutationObserver callback doesn't fire for EMBED nodes

本文关键字:节点 EMBED 回调 MutationObserver      更新时间:2023-09-26

由于某种原因,下面的代码片段只记录了1000多次"false",但从来没有记录过"true"。我不知道为什么,因为它似乎对任何其他元素都有效。

// 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);

我正在测试这个页面上的代码,在最新的Opera:

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

(如果你使用最新的Opera,它应该是一个Flash视频实现与嵌入,但在其他浏览器它可能是视频。)

你知道我做错了什么吗?

target是发生了变化的元素。当一个元素被插入时,改变的不是那个元素,而是它的父元素。检查mutation.target.nodeName == 'EMBED'将检查嵌入元素的attributes, childListcharacterData是否发生了变化,如果它们没有变化。如果您需要查看embed元素本身何时插入,则需要从父元素的角度查看它,例如

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');
  });
});