MutationObserver as a clever javascript workaround

For this weekend’s hackathon I worked on a hackathon project I had thought about for awhile… an anti auto correct that should be more like natural paper and pencil, and not automatically show the answer when you click on a misspelled word (not great for learning, Google Docs!) This should be useful for learners especially during a pandemic.

As Google Docs is perhaps the most used online word processor service, this project starts with that as a starting point. This presents some interesting challenges though:

First of all, while in the google doc editor, in the F12 console run “document.getSelection()”. You won’t see a useful selection or node like in any other page – in fact you can see that the cursor and text nodes of the document are managed by their own special Kix editor. As with most Google products there isn’t documented js and if you look in the script inspector you will see minified variable names – generally in any js minifier, the minified variables are not the globals and not ones you can directly access.

Instead, you can see the cursor is a “.kix-cursor” class element and other elements you may want to watch for. In times like this you may want to have an on-attribute-changed event to see something changes its style attribute, positioning, etc. Or what about an on-subnodes-changed event… guess what, there is such an event you can make in a round-about way with MutationObserver!

As you can see in the documentation, the general pattern is:

var myobserver = new MutationObserver(function(mutationsList, observer) {
    (Your code looking at mutationsList and reacting appropriately)
}
myobserver.observe(document.querySelector('.somecssselector', {subtree: true, childList: true, attributes: true });

As always your code in the observer should console.log(something) to see what attributes and objects you can access. That final object with childList, attributes, subtree should only have the ones that you want to be listening on.

Leave a Reply

Your email address will not be published. Required fields are marked *

× one = one