chrome MutationObserver用于新的段落文本 [英] chrome MutationObserver for new paragraph text
问题描述
我还没有真正理解如何使用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扩展程序的内容脚本中。为什么它不工作?任何帮助,将不胜感激。感谢!
-
observer.observe
应该观察添加了新的p
元素或者document.body
的父/容器元素。 / p>
-
observer.observe($('。some-container-selector')[0],.... 。
-
observer.observe(document.body,.....
-
在回调中,您应该检查添加的节点是否实际上是
p
: p>
$ b
mutations.forEach(function(mutation){
Array.prototype.forEach.call(mutation.addedNodes,function(node ){
if(node.nodeType!= 1)return; //只处理Node.ELEMENT_NODE
if(node.localName!='p'){//不是P,但可能是带P的DIV在
节点内= node.querySelector('p');
如果(!node)返回;
}
//现在我们有P节点
控制台。 log(Got P!,node);
});
});
$ b $ hr $
作为一种替代方案,我可以重复使用这个函数好几年,用一个更丑陋但更快的for循环:
函数setMutationHandler(baseNode,selector,cb){
new MutationObserver(function(mutations){
for(var i = 0,ml = mutations.length,m; (i< ml)&& (M =突变[I]);对于(var j = 0,nodes = m.addedNodes,nl = nodes.length,n;(jif((n = n.matches(selector)?[n]:n.querySelectorAll(selector))&& n.length)
if (!cb.call(this,[] .slice.call(n)))
return;
})。observe(baseNode,{subtree:true,childList:true});
$ b $ p
$ b用法(这里的回调只接收
p
元素在.some-container-class
)下:
<$ c (节点){
nodes.forEach(function(node)){
console.log(Got node,node) ;
//做某事
});
//this.disconnect(); //断开观察者,对一次性作业有用
//返回true; / /继续枚举当前批次的变化
});
与setMutationHandler循环相比,最后一个for循环很少发生,因此它可能会被更多简洁
[]。forEach.call(nodes,...
或Array.prototype.forEach.call(nodes,....
或jQuery包装与.each
。
Chrome版本的PPS必须在34之前脚本的开始:
pre $if(!Element.prototype.matches)
Element.prototype.matches = Element .prototype.webkitMatchesSelector;
I haven't really understood quite yet how to use the mutationObserver but what I currently have seems somewhat right... I'd like to do an action every time new
p
tag appears within the code.. Here is my code thus far: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 });
This code is within a content script in a chrome extension. Why isn't it working? Any help would be appreciated. Thanks!
解决方案observer.observe
should observe the parent/container element to which the newp
elements are added ordocument.body
.observer.observe($('.some-container-selector')[0], .....
observer.observe(document.body, .....
inside the callback you should check whether the added node is actually
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); }); });
As an alternative here's a function I reuse for several years, with an uglier but much faster for-loop:
function setMutationHandler(baseNode, selector, cb) { new MutationObserver(function(mutations) { for (var i=0, ml=mutations.length, m; (i<ml) && (m=mutations[i]); i++) for (var j=0, nodes=m.addedNodes, nl=nodes.length, n; (j<nl) && (n=nodes[j]); j++) if (n.nodeType == 1) if ((n = n.matches(selector) ? [n] : n.querySelectorAll(selector)) && n.length) if (!cb.call(this, [].slice.call(n))) return; }).observe(baseNode, {subtree:true, childList:true}); }
Usage (here the callback would receive only
p
elements under.some-container-class
):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 });
The last for-loop occurs quite rarely comparing to the setMutationHandler's loops so it may be replaced with a more concise
[].forEach.call(nodes, ...
orArray.prototype.forEach.call(nodes, ....
or jQuery wrapper with.each
.P.P.S. for Chrome pre-34 this is required somewhere at the start of the script:
if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.webkitMatchesSelector;
这篇关于chrome MutationObserver用于新的段落文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-