0

I've made a simple chrome extension which runs content script on page load. It changes src attribiute of img tags. How do I make it run every time a website gets new img tags? For example if you scroll down on facebook new content is added, I'd like to change those new images to my own. Maybe there's a better way? Thanks in advance.

TheHardew
  • 399
  • 4
  • 12

1 Answers1

2

I would create a mutation observer and add it into a Content Script that is injected after page loads.

The code below is listening for images being added to the body element, and an event is fired every second to simulate an image being added to the DOM

// select the target node
var target = document.querySelector('body');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      var nodes = mutation.addedNodes;
      var node;
      for(var n = 0; node = nodes[n], n < nodes.length; n++) {
          if(node.tagName == "IMG") {
            console.log("Image found");
          }
      };
    });
});

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

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


setInterval(function() {
  var i = new Image();

  document.body.appendChild(i);

}, 1000);
Kinlan
  • 16,315
  • 5
  • 56
  • 88