mutationObserver on web.whatsapp.com
The node you're looking for may be added as a child of its encompassing element so normally you would need to dig every node's children, but your case is simpler because the node has an id, which means you can use the insanely fast getElementById instead of digging. Here's the entire code:
waitForId('side').then(el => {
console.log(el);
});
function waitForId(id, nodeToObserve = document) {
const el = document.getElementById(id);
return el ?
Promise.resolve(el) :
new Promise(resolve => {
new MutationObserver((mutations, observer) => {
const el = document.getElementById(id);
if (el) {
observer.disconnect();
resolve(el);
}
}).observe(nodeToObserve, {childList: true, subtree: true});
});
}
normally you would need to dig every node's children
I thought that's what {childList: true, subtree: true}
does?
Thanks for your reply, I'll try to understand, learn and adapt.
/edit Works like a charm. First time I hear about the promise-object. Gotta read some docs.
If the page script adds an element that already has child nodes, neither subtree nor childList will expand individual nodes in the addedNodes
array, there'll be just one node. The subtree
mode simply allows the observer to see mutations in the nested child nodes, without it only the immediate children of the observed node would be reported.
Ah ok that's the point I didn't know, so it couldn't work.
mutationObserver on web.whatsapp.com
Hi, I want a function to only execute if
#side
element is present (that is when you are logged in).Unfortunately my mutationObserver does not work and I don't know why:
The element
#side
seems not to be in the list but it is added to#app
after login.I'm not good at JS, but there are no syntax errors, it's a basic problem.
Screenshots: https://imgur.com/a/3sNUfS2