我正在尝试使用突变观察器,但我发现在不降低浏览器速度的情况下很难实现。也许这只是我的实现,但我希望有人看一下,看看是否有任何可以改进的地方。
我还尝试检查 p
标记的突变,但我似乎无法弄清楚。现在我正在检查 document.body
的突变,因为我不知道如何实现 p
。
var arrayOfP = $("p").text(); //Get p tags
var observer = new WebKitMutationObserver(function(mutations) {
tempArrayOfP = $("p").text(); //Get p after mutation
tempArrayOfP = tempArrayOfP.replace(arrayOfP,''); //Get the difference between before and after mutation (this line doesn't seem to work...
arrayOfP = $("p").text(); //Store new case of current p tags
chrome.runtime.sendMessage(tempArrayOfP, manageResponse); //Send p tags to other file in chrome extension
});
observer.observe(document.body, { attributes: true, childList: true, characterData: true });
有什么想法吗? tempArrayOfP 替换似乎不起作用,目前我的 chrome 扩展正在发送消息时重做页面上的所有内容。
感谢您的帮助。谢谢。
最佳答案
传递给回调的突变可以提供旧值和新值,这将使您不必为每个突变遍历 DOM。
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
var oldValue, newValue;
if(mutation.type === 'characterData' &&
mutation.target.parentNode &&
mutation.target.parentNode.nodeName.toLowerCase() === 'p')
{
oldValue = mutation.oldValue;
newValue = mutation.target.textContent;
} else if(mutation.target.nodeName.toLowerCase() === 'p' &&
mutation.addedNodes.length &&
mutation.removedNodes.length)
{
oldValue = mutation.removedNodes[0].textContent;
newValue = mutation.addedNodes[0].textContent;
} else {
return;
}
// do stuff
document.write('old: ' + oldValue + ', new: ' + newValue);
});
});
observer.observe(document.body, { characterDataOldValue: true, subtree: true, childList: true, characterData: true });
// test
document.querySelector('p').textContent = 'good bye';
<p>hello world</p>
对于提取新旧文本之间的差异,您的方法假设突变没有删除任何文本,或在现有文本之间插入文本。如果发生这种情况,replace 中的字符串将不会匹配任何内容。
关于javascript - 让突变观察者更快、更少占用资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425192/