【问题标题】:JS - How do i run script again when new text elements are added to a pageJS - 当新的文本元素添加到页面时,我如何再次运行脚本
【发布时间】:2018-10-13 13:57:52
【问题描述】:

浏览 StackOverflow 一段时间后,我找不到解决方案。对于一个学校项目,我们制作了一个 chrome/firefox 扩展,它使用我们自己定制的过滤器替换网站上的单词。我们已经能够对 URL 更改做出反应,但是当网站更新而不更改 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 的情况下再次运行我们的扩展程序,但我们不知道该怎么做。有什么建议吗?

【问题讨论】:

  • 变异记录不一定包含addedNodes数组中所有递归添加的节点。相反通常是正确的:仅列出顶部节点,因此您需要递归枚举其树。见How to change the HTML content as it's loading on the page
  • 英语不是我的第一语言,所以我不确定递归枚举树的意思。我假设您的意思是使用 for 循环遍历每个节点?不管怎样,谢谢你的链接,我看看能不能从你链接的帖子中弄清楚。

标签: javascript google-chrome-extension


【解决方案1】:

一个想法可能是对 Element 构造函数 (Element.prototype.append) 的 append 函数和 Node 构造函数 (Node.prototype.appendChild) 的 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);

                           };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 2019-03-25
    • 2014-02-03
    • 2011-11-18
    • 2014-11-15
    • 1970-01-01
    • 2023-04-02
    • 2019-03-17
    相关资源
    最近更新 更多