0

I'm learning to create Firefox extensions. Now I wrote a simple test extension that changes all images on the page to my image:

var images = document.getElementsByTagName('img');
var myimgURL = browser.extension.getURL("images/myimg.jpg"); 
for (var i=0; i<images.length; i++){
  var img = images[i];
  img.setAttribute("src", myimgURL);
}

It works for static pages but doesn't work for dynamically loaded content via AJAX like Facebook feed.

How should I change my code to work with dynamic content. Thanks!

UPD: Now I try to use MutationObserver to monitor changes but it seems not working for me. Here is my code:

var images = document.getElementsByTagName('img');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
  alert("Mutation!");
  });    
});

var config = { attributes: true, childList: true, characterData: true };

observer.observe(images, config);

I open Facebook page, scroll it to load new images but don't get any alerts. What's wrong in my code now?

  • `How should I change my code to work with dynamic content?` you'll need to somehow detect when the page is changed - eg [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) – Jaromanda X Oct 06 '17 at 23:03
  • This answer specifically includes other options available to extensions: [Is there a JavaScript/jQuery DOM change listener?](https://stackoverflow.com/a/39508954) – Makyen Oct 07 '17 at 05:24
  • Thanks! I try to use MutationObserver but it seems not working for me, I updated my main post. What's wrong with it? – Alexander Rysev Oct 07 '17 at 10:23

0 Answers0