Is it possible to observe class changes on the DOM of a website through a chrome extension?

Viewed 965

I'm trying to triger an action when a especific class changes in a external web site. Is that possible?

2 Answers

Attach a MutationObserver to the element and watch for attribute changes. When a mutation occurs, check if the attributeName of the mutation is class:

const div = document.querySelector('div');

new MutationObserver((mutations) => {
  if (mutations[0].attributeName === 'class') {
    console.log('class change seen');
  }
})
  .observe(div, { attributes: true });

setTimeout(() => {
  div.classList.add('foo');
}, 2000);
<div></div>

I am only posting my answer because I had already worked on it and it will work on the parent element of the DOM node you want to monitor but @CertainPerformance answer will work for single element.

You basically want to use a MutationObserver to watch DOM changes. The following example/demo shows how you can monitor the changes of any DOM nodes under any container:

// The original app code
function changeColor() {
  let children = document.getElementById('container').children,      
      itemIndex = Math.random() * children.length | 0
      
  children.item(itemIndex).classList.toggle('red')
}

// The foreign code observer
let observer = new MutationObserver(function(list){
  for ( let mutation of list) {
    if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
      let node = mutation.target
      console.log(`${node.nodeName} class changed to: ${node.className}`)
    }
  }
})

observer.observe(document.getElementById('container'), {
  attributes: true,
  childList: true,
  subtree: true
})
.red {
  color: red;
}
<div id="container">
  <h1>Hello World</h1>
  <p>Hello World 1</p>
  
  <button onClick="changeColor()">Change a Color</button>
</div>

Related