How To Execute Javascript Code After An Element Is Created Without Jquery?
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 frame
Solution 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.
Solution 2:
If you're writing a Chrome extension, you should probably use the chrome.webRequest
API and onCompleted
event
chrome.webRequest.onCompleted.addListener(function callback)
Post a Comment for "How To Execute Javascript Code After An Element Is Created Without Jquery?"