Sleazy Fork is available in English.

討論 » 開發

mutationObserver on web.whatsapp.com

§
發表於:2018-08-15
編輯:2018-08-15

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

wOxxOm管理員
§
發表於:2018-08-15

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});
    });
}
§
發表於:2018-08-15
編輯:2018-08-15

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.

wOxxOm管理員
§
發表於:2018-08-15
編輯:2018-08-15

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.

§
發表於:2018-08-15

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

發表回覆

登入以回復