Reputation: 651
I am developing a chrome extension which would modify an element in a website. That website sends a lot of ajax call after loading the main document to get page contents (GWT framework architecture). I need to modify the content of that webpage and the element that I want to modify will be created only after all the ajax calls.
let's assume that the id of element that i want to modify is #idContainer > div > div.container.container\--wider.\\30
, which will be available only after the completion of the ajax call.
so how to execute a js code (via chrome extension -> content script) after this element is available.
Note: I have seen many similar questions in stackOverflow but none of them have answers without using jQuery.
Upvotes: 2
Views: 500
Reputation: 20430
Consider using a Mutation Observer. Here is an example of some of my projects where I had to solve the exact same problem.
// observer callback
const callback = (mutations) => {
const matching = [];
for (const {addedNodes} of mutations) { // for each mutation
for (const node of addedNodes) { // iterate through all added nodes
if (node.nodeType !== Node.ELEMENT_NODE) {
continue; // only react to real element nodes
}
if (node.children[0]) { // Here you can check for what you want
matching.push(...node.getElementsByTagName('pre'));
}
}
}
if (matching.length === 2) { // I needed the second pre tag
ipcRenderer.send('note-result', matching[1].innerText);
}
};
// intialize the observer with the callback
const observer = new MutationObserver(callback);
// pass a targetNode and an options object in the observe method
observer.observe(document.body, {attributes: true, childList: true, subtree: true});
In this example I was interested in the textContent of the second "pre" tag that appeared in the DOM.
You can also stop observing with the disconnect method:
observer.disconnect();
You have to adjust the code somewhat to your particular use case but this is the gist of using a mutation observer.
Upvotes: 1
Reputation: 20039
If you're writing a Chrome extension, you should probably use the chrome.webRequest
API and onCompleted
event
chrome.webRequest.onCompleted.addListener(function callback)
Upvotes: 1