Này người xa lạ!

Còn chờ gì nữa mà không mau đăng nhập hoặc đăng ký để cùng tham gia thảo luận với cộng đồng!

mutationObserver on web.whatsapp.com

đã sửa August 2018 trong Phát triển Firefox

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

Bình luận

  • 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});
        });
    }
    
  • đã sửa August 2018 Firefox

    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.

  • đã sửa August 2018 Chrome

    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.

Đăng nhập hoặc Đăng ký để gửi bình luận.