Warm tip: This article is reproduced from stackoverflow.com, please click
dom-events events google-apps-script iframe javascript

Google apps script get keycode events from document

发布于 2020-04-15 10:48:02

I'm trying to be able to modify parts of a Google document while the user is typing.

Specifically, I want to add a feature to indent multiple lines of text. Meaning when the user selects multiple lines of text, and then clicks the "tab" key, it should indent all of those lines

To do this, I think I have to get the current keyCode of whatever the user is typing, in addition to reading the selection using:

 var doc = DocumentApp.getActiveDocument().getCursor();
    var els = doc.getElement(),
    txt = els.asText().getText()

which I already have working. But the problem:

on my client side, when I do:

window.addEventListener("keyup", function(e) {
        console.log(e.keyCode);
    })

that only activates when the user has selected the sidebar, but not when the user types in the google document itself.

I understand why this is, as the app runs in an iframe within an iframe, but still I thought there might be a way to somehow get what key was pressed, or at least somehow determine if the user tried to press the tab key or not.

So: is there any way to detect if the user pressed the tab key, or is there some other kind of way to indent multiple lines easily with google apps script? Preferably not requiring the user to click a button on the app script itself, but if that's the only way, then so be it... but is there any possible way to get what keys were pressed by the user on the google doc itself?

Questioner
bluejayke
Viewed
46
Diego 2020-02-04 11:56

It's not possible in Google Docs. You're asking for an "onEdit" or "onChange" trigger, but unfortunately, they're only available in Google Sheets and not in Docs. You can use the table listed in this Add-on triggers page to see what triggers are available across all of Apps Script (not just add-ons).