I would recommend either using a setInterval
which would allow you to overwrite any changes made after the additional content is loaded. Or a MutationObserver
which would allow you watch all incoming changes and make updates accordingly.
setInterval Example:
setInterval(() => {
// Check to see if your modification is on the page
// If not then re-add it
if (!document.body.innerHTML.includes('<div id="target">')) {
// Call your function to modify the content
yourFunction();
}
// Run every second
}, 1000);
MutationObserver Example:
const observeMutations = (targetNode, baseElm, addedElm, cb) => {
const observer = new MutationObserver((mutationsList) => {
// Iterate through each incoming change to the DOM
for (const mutation of mutationsList) {
const HTML = String(mutation.target.innerHTML);
// Feel free to modify this to fit your use case
// Call function if the base element exists, but your modification does not
if (HTML.includes(baseElm) && !HTML.includes(addedElm)) {
// Call your function to apply to the page
cb();
break;
}
}
});
// Configuration options:
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe#parameters
const options = {
attributes: true,
childList: true,
subtree: true,
};
observer.observe(targetNode, options);
// Disconnect observer on a timer for slow loading elements
setTimeout(() => observer.disconnect(), 15000);
};
observeMutations(<your inputs>)
References
setInverval: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
MutationObserver:https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver