Home > Back-end >  Disconnect MutationObserver wrapped in self invoking function
Disconnect MutationObserver wrapped in self invoking function

Time:03-06

I have created a JavaScript that uses MutationObserver to watch for changes to a website in the console. The script would retrieve some values from a div, log the accumulated sum and also create some elements on the page (omitted in the code below for simplicity).

I wrap the MutationObserver in a self Invoking function to prevent the variables from colliding with the ones used by the website.

Occasionally the script may fail (the script is not robust enough to deal with some differences in pages) and what I am doing is to log out of the page, paste a different script onto the console to make it work again. Or else the sum would be incorrect and the elements would be created in the wrong place.

I understand that the MutationObserver is on its own scope so observer.disconnect(); would not work. Is there other way to disconnect the MutationObserver in the console without having to refresh/log out of the page?

Here is the simplified version of my code:

(function () {  
    const targetNode = document.querySelector('div.content')
    const observerOptions = { childList: true, attributes: false, subtree: false }
    const callback = function (mutationsList, observer) {
      for (const mutation of mutationsList) {
        if (mutation.removedNodes.length > 0 && (mutation.removedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
        if (mutation.addedNodes.length > 0 && (mutation.addedNodes[0].classList.contains('some-view'))) {
            // do something here
        }
      }
    }
  
    const observer = new MutationObserver(callback)
    observer.observe(targetNode, observerOptions)
  })()

Thank you.

CodePudding user response:

It would be simple enough to assign the observer to the window, eg

    window.observer = new MutationObserver(callback)
    observer.observe(targetNode, observerOptions)
})()

and then type into the console observer.disconnect() - but a more maintainable solution would be to

  • insert a button onto the page that calls .disconnect() when clicked, or
  • figure out what exactly is failing, and tweak the logic to work around that
  • Related