How to detect undetected innerText change on DOM element with MutationObserver?

2.1k views Asked by At

I'm trying to write a browser extension that detects changes to the innerText of an HTML element on Facebook. For reasons I can't discern, when the only thing that changes on the target element is the innerText (or innerHTML), no mutation is observed.

However, if I write my own test program outside of Facebook, trying to detect an innerText change, it does create an observable DOM mutation. So first, here's an example of it working as expected (fiddle here):

HTML:

<div id="trackmychanges">starting text</div>
<button id="button">press to trigger change on text above</button>
<div id="status"></div>

JS:

var target = document.getElementById('trackmychanges');

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    console.log(mutation.type);
    $('#status').text("got a "+mutation.type+" mutation!");
  });    
});

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

observer.observe(target, config);

$('#button').click(function() {
  $('#status').text("changing...");
  setTimeout(function() {
    $('#trackmychanges').text("new text "+Math.random());
  }, 200);
})

But on Facebook this method doesn't work. The node whose innerText I'm trying to track there has the class name UFILikeLink. The following example code (paste into the Javascript console with Facebook running to test), sets up an observer as above.

Find the first "Like" button on the page (e.g. on the News Feed) and click it, or select a "reaction" (such as Wow, Love, Haha, etc.). Doing so will likely trigger a mutation as expected (because the first click on a "Like" also adds some attributes and children). However, if you use the reactions popup to select "Wow" and then use it again to select "Haha" or "Sad", then it doesn't work. In this case, because the only thing changing on the element is the innerText, nothing gets triggered. (Moving from Haha to Sad to Wow in any order has this effect because no attributes or children get modified in such a case---only the innerText). If you watch this node in the console's elements pane, you'll see the innerText change there, but still no mutation is observed.

var target = document.querySelector('.UFILikeLink');
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) { console.log(mutation.type); });    
});   
var config = { attributes: true, childList: true, characterData: true };
observer.observe(target, config);

Is it possible to get notified of these innerText changes using a MutationObserver?

0

There are 0 answers