Discussioni » Sviluppo

mutationObserver on web.whatsapp.com

§
Pubblicato: 15/08/2018
Modificato: 15/08/2018

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:

    // Execute only when logged in (sidebar present)
    // Create instance of observer
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            mutation.addedNodes.forEach(function(node){
                //console.log(node);
                if (node.id == "side") {
                    // do my stuff
                    console.log("Stuff done!");
                    //observer.disconnect();
                }
            });
        });
    });
    // Start observation
    observer.observe(document.getElementById("app"), {childList: true, subtree: true} );

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

woxxomMod
§
Pubblicato: 15/08/2018

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});
    });
}
§
Pubblicato: 15/08/2018
Modificato: 15/08/2018

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.

woxxomMod
§
Pubblicato: 15/08/2018
Modificato: 15/08/2018

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.

§
Pubblicato: 15/08/2018

Ah ok that's the point I didn't know, so it couldn't work.

Pubblica risposta

Accedi per pubblicare una risposta.