Привет, незнакомец!

Похоже, вы здесь новенький. Чтобы принять участие, нажмите одну из кнопок ниже!

mutationObserver on web.whatsapp.com

отредактировано August 2018 Раздел: Разработка Firefox

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) {
                if (node.id == "side") {
                    // do my stuff
                    console.log("Stuff done!");
    // 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.



  • 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 => {
    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) {
          }).observe(nodeToObserve, {childList: true, subtree: true});
  • отредактировано 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.

    Works like a charm. First time I hear about the promise-object. Gotta read some docs.

  • отредактировано 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.

Войдите или Зарегистрируйтесь чтобы комментировать.