Frage

I'm writing a userscript to replace every occurrence of a word in a page with another word (think the cloud -> my butt). It's based on this script https://github.com/panicsteve/cloud-to-butt/blob/master/Source/content_script.js

Normally this is easy. I just need to run it when the page finished loading. However, I'm doing this to the Facebook news feed, and the script only applies to the contents that were load initially. When I scroll down and new contents are loaded, the text in those new contents are not touched by the script.

How can I make it so that when new contents are loaded when I scroll down the page, the script runs again?

War es hilfreich?

Lösung 2

In the end I used MutationObserver:

// select the target node for mutation observation
var target = document.body;

// create an observer instance
var observer = new MutationObserver(function(mutations) { // mutations: an array of MutationRecord objects
    mutations.forEach(function(mutation) {
        var addedList = mutation.addedNodes;
        for (var i = 0; i < addedList.length; ++i) {
            // do something with addedList[i]
        }
    });    
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true, subtree: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

Andere Tipps

It's ugly, but using a window.setTimeout() function could do it... p-code, of course.

var updateStuff() {
  var els = document.GetElementsByClassNames("ThingsToLookFor");

  for (var i = 0; i < els.length; i++) {
    var el = els[i];
    if (el["data-touched"]) {
      // We've seen this
      continue
    }

    // Update the element or whatever you do
    el["data-touched"] = true;

    window.setTimeout(updateStuff, 250);
  }
}
// Kick it off
updateStuff();

Don't actually use data-touched -- I didn't feel like looking for the real syntax to update data-* stuff, or you could use el.setAttribute("data-touched", true)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top