Detecting keyboard input in Google Docs with JavaScript

I’m working on a script for Google Docs and I need to catch keyboard events in the main editing area. I’ve tried using keypress, keyup, and keydown events, but nothing seems to work. Here’s what I’ve attempted:

(function() {
  const elements = document.querySelectorAll('*');
  elements.forEach(el => {
    el.addEventListener('keypress', () => console.log('Key pressed'));
    el.addEventListener('keyup', () => console.log('Key released'));
    el.addEventListener('keydown', () => console.log('Key down'));
  });
})();

This code works fine on other websites, but not in Google Docs. I’ve checked with browser dev tools, and it looks like these events aren’t firing when I type in the main document area.

The editing pane seems to be made up of special divs that handle text input. Does anyone know how to capture keyboard events in this situation? I’m stuck and could really use some help. Thanks!

I’ve faced this challenge before, and it’s quite tricky. Google Docs uses a sophisticated ContentEditable system that bypasses standard DOM events. One workaround I’ve found effective is utilizing the MutationObserver API. It allows you to detect changes in the DOM, which can indirectly capture typing events.

Here’s a basic implementation:

const targetNode = document.querySelector('.kix-appview-editor');
const config = { childList: true, subtree: true };

const callback = function(mutationsList, observer) {
    for(let mutation of mutationsList) {
        if (mutation.type === 'childList') {
            console.log('Content changed');
        }
    }
};

const observer = new MutationObserver(callback);
observer.observe(targetNode, config);

This approach isn’t perfect, but it’s the closest I’ve gotten to real-time input detection in Google Docs without resorting to Google Apps Script. Just remember to adjust the selector for the target node based on your specific use case.

i had similar issues w/ google docs. it uses custom components that don’t fire regular DOM events. try Google Apps Script instead - it has built-in methods for doc editing. check out the DocumentApp class, it might have what u need for keyboard input. good luck!

You’re right, Google Docs uses a complex system that doesn’t play well with standard DOM events. I’ve encountered this issue before. Instead of trying to capture keyboard events directly, consider using the Google Apps Script Editor. It provides an API specifically designed for Google Docs. Look into the ‘onEdit’ trigger - it fires whenever changes are made to the document. While it’s not exactly real-time keyboard input, it’s the closest you can get within Google Docs’ environment. Remember to set up proper authorization for your script to interact with the document. Hope this helps point you in the right direction.