user2381114
user2381114

Reputation: 147

Reinitialising content script after Ajax load?

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:

Upvotes: 0

Views: 481

Answers (1)

Xan
Xan

Reputation: 77591

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.

Upvotes: 1

Related Questions