Using mutationObserver doesn't seem to track a changing table in the DOM

I am trying to write a simple chrome extension that modifies table values ​​in the DOM. The important thing is that the web page uses ajax commands to create and modify the contents of this table. (Firstly, there is nothing displayed on the page. Then you click on the link and using ajax-request (without reloading the page) a table will be created, and after that, clicking on other links, this table will be changed).

Here the code that I use to listen to the table changes:

var target = document.querySelector('#my-table');

var observer = new MutationObserver(function (mutations) {
    mutations.forEach(function (mutation) {
        alert('The table has appeared');
    });
});

var config = {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true
};

observer.observe(target, config);

observer.disconnect();

The problem is that nothing will happen when I click on the link on the page that will change the table. And when I checked the chrome console to debug my work, I saw that it gave me this error as soon as the page loads:

Uncaught NotFoundError: '' 'MutationObserver': node null

, . - ? ps: :

"manifest_version": 2,

  "name": "MyExtension",
  "description": "Testing the Content Script api",
  "version": "1.0",

  "content_scripts": [
    {
      "matches": ["www.myWebsite.com"],
      "js": ["script.js"]
    }
  ],

  "browser_action": {
    "default_icon": "icon.png"
  }
}
+4
1

, .

  var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      mutation.addedNodes.forEach(function(node) {
        if (node.id == 'my-table') { // or node.getElementsByClassName(..).length or whatever
          console.log('table has appeared.');
        });
      });
    });
  });
  observer.observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false,
  });

, , :

  var observer = new MutationObserver(function() {
    if (document.getElementById('my-table')) {
      console.log('table has appeared.');
    }
  });
  observer.observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false,
  });

ID, , id .

+7

All Articles