Google docs – Access text changes realtime

If a browser plugin is an appropriate way to deliver the feature, it should be possible to listen to changes that Google Docs makes to the DOM when it updates the page content.

// This div contains all of the page content and not much else, in my rudimentary testing.
var pageRoot = document.getElementsByClassName('kix-appview-editor')[0].firstChild;

var observer = new MutationObserver(handleNewChanges);
observer.observe(pageRoot, {
  subtree: true,
  childList: true,
  attributes: false,
});

// Later, you can stop observing
observer.disconnect();

Your handleNewChanges function will be called any time the content of the DOM changes, with a list of changes. The changes are pretty messy, but

  • inconsequential changes (like the user selecting some text) can be filtered by looking at the added and removed nodes,
  • you can walk up the DOM tree to find the location of the changes in the document, and
  • you can use someNode.innerText to get the actual content.

By observing the changes and keeping some document state, you should be able to determine when the sorts of changes that you care about happen.


This seems like a good fit for your use case, because

  • No remote servers are needed. The data flow would look more like this, entirely within the browser tab:

    ---------------                   ----------        
    | Google Docs | <=  fetch doc  <= |  Your  |
    |  Document   | => DOM changes => | Module |
    ---------------                   ----------
    
  • The updates are synchronised with the document visually updating, which feels like the natural thing to trigger this.

  • The amount of bookkeeping that you need to do to parse each DOM change can probably be constant (that is, without looping over the document content). This would mean that the overhead that the observing adds is constant, so it should scale to any sized document.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)