I have a puppeteer project in which I'm waiting for some form of information on an Element. For example, in the header, I'm waiting for some new child Nodes.
<div id="outside">
</div>
and then after some time
<div id="outside">
<div id='inside'>
</div>
</div>
is there a way for me to add an event listener to check when the HTML has been changed?
something like
page.addListener('#outside', () => {
console.log('event fired');
}
You can try with MutationObserver
// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
const targetNode = document.querySelector('#outside');
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
targetNode.insertAdjacentHTML('beforeend', "<div id='inside'>Child</div>"); // Add child
targetNode.classList.add('.child'); // Modify attribute
document.querySelector('#inside').style.marginLeft = '15px';
<div id="outside">Parent
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With