Upcoming DD
Upcoming DD

Reputation: 21

JS - How do i run script again when new text elements are added to a page

After browsing through StackOverflow for a while i weren't able to find a solution. For a school project we've made a chrome/firefox extension that replaces words on websites using a filter we customize ourselves. We've been able to react to URL changes, but we can't get it to update when the site updates without changing the URL, like when you scroll down on facebook or youtube and new content is automatically added.

We've tried using mutationObserver but it haven't proven succesful (No errors but no console logs either, so it isn't triggered)

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 });  

Basically we just want to run our extension again once a site changes without the url updating, but we can't figure out how to. Any suggestion?

Upvotes: 2

Views: 86

Answers (1)

Redu
Redu

Reputation: 26161

One idea could be to monkey patch the append function of the Element constructor (Element.prototype.append) and the appendChild function of the Node constructor (Node.prototype.appendChild). Not so great but should do the job.

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);

                           };

Upvotes: 1

Related Questions