Google Apps Script HTML - How to make a keyboard event trigger from an entire document rather than just a button?

2k views Asked by At

For Google Apps Script for Google Docs, in the Sidebar.html file I use this code(simplified to remove irrelevant parts):

<div class="sidebar branding-below">
  <form>
   <div class="block" id="button-bar">
      <button id="some-action" class="action">Action</button>
    </div>
  </form>
</div>

<script>

  $(function() {
    $('#some-action').click(doSomething);           //call the method below on button click
    google.script.run.withSuccessHandler(loadPreferences)
        .withFailureHandler(showError).getPreferences();  //not sure what this does
  });

  $(document).keydown(function(e){             //only applies to button??
    //output whatever key was pressed under the button
    var div = $('<div id="clickmsg" class="text">' + 'KeyPressed: ' + e.which + '</div>');
    $('#button-bar').after(div);
    //Detect CTRL + q keydown combo, which should be unused in windows and chrome
    if(e.ctrlKey && e.keyCode == 81){
      var div = $('<div id="clickmsg" class="text">' + 'Ctrl+Q detected' + '</div>');
      $('#button-bar').after(div);
      doSomething();                           //calls the method below
    }
  });

  function doSomething() {
    this.disabled = true;
    $('#error').remove();
    google.script.run
        [some code...] //doStuff
  }
</script>

The doSomething() only triggers when I have tabbed to the button. Thus, as long as the button is still under tabbed selection, then the keys that I am pressing are displayed below it. However, under any circumstance where I have not tabbed to the button, no matter what keys are pressed, this key press code does not output anything.

Note that I use $(document).keydown, but never defined "document" anywhere. However, somehow it automatically binds to the button in the sidebar. Why does this happen, instead of returning an error? How do I make it detect keyboard shortcuts in all of the google doc, even if the user is just typing? Is HTML even the right way to detect this?

I know this is (probably) possible because of this post about an issue that I used the keybind code from, the issue here, where the person who posted toe code said that "the new IFRAME mode in HtmlService does allow for key codes to be passed on to Add-ons", as long as the user has "click[ed] on / activate[d] the sidebar first."

1

There are 1 answers

0
Mogsdad On BEST ANSWER

Your HTML gets wrapped by the HTML service, like this:

<iframe>
  <!DOCTYPE html>
    <more boilerplate...>
    ...

      your html

     ...
</iframe>

So, document is defined, and has a scope limited to the iframe. Since you only have one element within your form, focus must be there for the document to receive events.

If your intent is to capture all keystrokes in the Google Doc, you will not be able to do that within a Google Apps Script. A browser extension may be able to, though.