2

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

If you're writing a Chrome extension, you should probably use the chrome.webRequest API and onCompleted event

chrome.webRequest.onCompleted.addListener(function callback)

1 Comment

Thanks for the suggestion. I think mutation observer will be better option here than chrome.webRequest API because on doing this i want to keep track of all ajax call happening on that page and trigger the script on completion of all the ajax calls which would be complex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.