chrome MutationObserver用于新段落文本

我还没有真正理解如何使用mutationObserver但我现在看起来有些正确……我想在代码中出现新的p标签时做一个动作..这是我的代码到目前为止:

 var target = $('p'); var observer = new WebKitMutationObserver(function(mutations) { mutations.forEach(function(mutation) { chrome.storage.sync.get({ getInjection: true }, function(getInject) { var getInjectionState = getInject.getInjection; if(getInjectionState == true) { arrayOfP = $("p").text(); chrome.runtime.sendMessage(arrayOfP, manageResponse); } }); }); }); observer.observe(target[0], { attributes: true, childList: true, characterData: true }); 

此代码位于chrome扩展程序的内容脚本中。 为什么不工作? 任何帮助,将不胜感激。 谢谢!

  1. observer.observe应该观察添加了新p元素的parent / container元素或document.body

    • observer.observe($('.some-container-selector')[0], .....
    • observer.observe(document.body, .....
  2. 在回调中你应该检查添加的节点是否实际是p

     mutations.forEach(function(mutation) { Array.prototype.forEach.call(mutation.addedNodes, function(node) { if (node.nodeType != 1) return; // only process Node.ELEMENT_NODE if (node.localName != 'p') { // not P but might be DIV with P inside node = node.querySelector('p'); if (!node) return; } // now we have our P node console.log("Got P!", node); }); }); 


作为一种替代方案,这是一个我重复使用了几年的函数,它具有更丑陋但更快的for循环:

 function setMutationHandler(baseNode, selector, cb) { new MutationObserver(function(mutations) { for (var i=0, ml=mutations.length, m; (i 

用法(这里的回调只接收.some-container-class下的p元素):

 setMutationHandler(document, '.some-container-class p', function(nodes) { nodes.forEach(function(node) { console.log("Got node", node); // do something }); //this.disconnect(); // disconnect the observer, useful for one-time jobs //return true; // continue enumerating current batch of mutations }); 

与setMutationHandler的循环相比,最后一个for循环很少发生,因此它可以用更简洁的[].forEach.call(nodes, ...Array.prototype.forEach.call(nodes, ....替换[].forEach.call(nodes, ...带有.each jQuery包装器。

PPS for Chrome pre-34在剧本开头的某处需要:

 if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.webkitMatchesSelector;