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?
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).
would it be possible with an extension though?
@bluejayke I'm not sure what you mean by "extension", but I'm pretty sure the answer is no. Google simply doesn't provide a way to pass key press info from the editor to Apps Script.
I mean a browser chrome extension, I was actually just able to do this after learnign about extensions, in the content-script: addEventListener("keyup", e=> { console.log(e.keyCode); }, true), and in manifest: , "match_about_blank":true, "all_frames": true and now when I type in the google doc, it console logs the keycode... the onyl question now is sending that data to the google app script, perhaps it can be on an interval to constantly check a server, or maybe there is a way for the google app script to read the postmessage from the extension??
@bluejayke Makes sense that it'd work through a Chrome extension. If that's what you're doing, then the simple hack would be to have the extension simulate an action (click the appropriate button) in the sidebar.
Oh interesting idea, like fill out an input field and then click a submit button, genius! I guess I'll have to find a way to get the extension to set the value of an element in an iframe within an iframe though