0

In my content script, I am going through the entire DOM and doing something to all <img> elements for example.

I am using onUpdated in my Background.js to check when a tab is opened and then executing the script.

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) { 
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            if(info.status == "complete") {
                chrome.tabs.sendMessage(tabs[0].id, function (response) {
                   // send data to content script etc.
                });
            }
        });
}

This works fine for content that isn't dynamically loaded - for example, on the Facebook news feed, it'll do what I want to all the images that are initially visible - but as I scroll down, new stories/photos etc are loaded (using AJAX? unsure) and of course these <img> elements are not affected by my content script.

How can I reload (or adjust would be better as I have to search the entire DOM and it's slow) my content script so that it works for this newly adjusted DOM? I couldn't find any tabs method here - https://developer.chrome.com/extensions/tabs mentioning this issue.

Tried:

  • adding all_frames : true in the manifest does nothing.
  • removing the info.status conditional also does nothing.
user2381114
  • 147
  • 2
  • 11
  • Your code is definitely strange. Why do you get `tabs[0].id` and the whole query thing when `tabId` is passed into the listener? – Xan Mar 14 '15 at 19:28
  • @Xan It's not my whole code just the essentials for this question, I am passing a lot of chrome.storage stuff through but yeah you are right will change it – user2381114 Mar 14 '15 at 19:31
  • Does this answer your question? [Is there a JavaScript / jQuery DOM change listener?](https://stackoverflow.com/questions/2844565/is-there-a-javascript-jquery-dom-change-listener) – al. Mar 22 '20 at 20:19

1 Answers1

1

You'll need to monitor the page for insertion of new images, for instance using MutationObserver or mutation-summary library. tabs events will not fire on page changes like those.

See this question for a discussion of methods to do so.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206