在浏览 StackOverflow 一段时间后,我找不到解决方案。对于一个学校项目,我们制作了一个 chrome/firefox 扩展,使用我们自己定制的过滤器替换网站上的文字。我们已经能够对 URL 更改使用react,但我们无法在不更改 URL 的情况下更新网站时更新它,例如当您在 facebook 或 youtube 上向下滚动并自动添加新内容时。
我们已经尝试使用 mutationObserver 但它没有被证明是成功的(没有错误但也没有控制台日志,所以它没有被触发)
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === "characterData") {
console.log(mutation.target);
} else {
for (var x = 0; x < mutation.addedNodes.length; x++) {
var node = mutation.addedNodes[x];
if (node.nodeType === Node.TEXT_NODE) {
console.log(node);
walk(document.body)
}
}
}
});
});
observer.observe(document, { childList: true, subtree: true, characterData: true });
基本上,我们只想在站点发生变化而 url 没有更新时再次运行我们的扩展程序,但我们不知道该怎么做。有什么建议吗?
最佳答案
一个想法可能是猴子修补 Element
构造函数 (Element.prototype.append
) 的 append
函数和 Node 构造器的 appendChild
函数 (Node.prototype.appendChild
)。不太好,但应该可以胜任。
Element.prototype.__append__ = Element.prototype.append;
Element.prototype.append = function(e){
console.log("Replacing some words in this element");
this.__append__(e);
};
Node.prototype.__appendChild__ = Node.prototype.appendChild;
Node.prototype.appendChild = function(e){
console.log("Replacing some words in this node");
this.__appendChild__(e);
};
关于javascript - JS - 当新文本元素添加到页面时如何再次运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50151895/