简体   繁体   中英

mutation Observer not initializing/working

I have an issue with my mutationobserver and I cannot seem to understand what is going on. my first check is to make sure mutationobserver is define and loaded on the page. Next I create my new mutationobserver and then if there are mutations, I wait until they are all finished and run a function.

The problem is is that the script is not create a new mutationobserver.

Here is my typical output, I only make it as far as my first console log.
//poll typeof good

On rare occasion, the mutationobserver will be created and I will get a full load of my logs, but it is 1 out of 10/20 times. I thought it might be a timing issue, but after setting my settimeout to 10 sec, it makes me doubt there is a timing issue.

My only other note is that this is being injected onto the page as the page loads, asynchronously. Not sure if that has anything to do with it, but figured I'd call it out

Any thoughts?

setTimeout(function () {

  if(window.MutationObserver && typeof MutationObserver === 'function'){

  console.log('poll typeof check');

  var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

       var optFilterSort = new MutationObserver(function(entries) {
       var optEntries = entries.length;
        console.log('poll optEntries ' + optEntries);
        if(entries.length >= optEntries){
          console.log('poll mutations complete');
          optStart();
       }
    });

  var optTargetFilter = document.querySelector(".mydiv");
  var optConfig = {
        attributes: !0,
        childList: !0,
        characterData: !0,
        subtree: !0
    };
  optFilterSort.observe(optTargetFilter,optConfig);
  
  
}

}, 10000);

Your "var optFilterSort..." exists only within the context of your function, called with the setTimeout callback function. Your created MutationObserver is effectly deleted once the setTimeout callback function has completed. https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver has an example for setting up a mutation observer object. You should be setting your mutation observer as a variable of the window or within a persisting context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM