Google Docs simulate keyboard
Asked Answered
I

2

7

I need to simulate keyboard in google docs with using JavaScript to be able print or erase characters on cursor position.
Unfortunately solutions with simulating keypress event didn't work for me. I tried with and without jQuery.
After some investigation I detected that Google Docs have virtual keyboard. Clicks on virtual keys calls this function:

C.MOa = function(a) {
  this.dispatchEvent(new Q(Td, {keyCode: a}))
};

Where Td is a string "action" and Q some Event class.
What is the correct way to send this event with java script? Is there other ways to simulate keyboard in Google Docs?

Inhuman answered 4/12, 2014 at 9:58 Comment(1)
Just as a note about jQuery event: Events emitted with $(elm).trigger(yourEvent) are no real events and do not do real DOM bubbling (at least the last time I looked into jQuery), cause of that those event are only detected by jQuery itself.Sedberry
C
6

Seems like Google Docs have special iframe to handle keyboard events. Here is it’s contents:

<html>
    <head></head>
    <body spellcheck="false" role="textbox" aria-label="Document content" contenteditable="true" style="background-color: transparent;"></body>
</html>

Just dispatch keyboard events to this document to print characters on google doc.

Copyboy answered 9/12, 2014 at 21:6 Comment(3)
is there an equivalent to this for google spreadsheets?Schaab
Does this still work after Google Docs' update to canvas based rendering instead of HTML based rendering?Benumb
Doesn't appear to.Coma
N
12

Paste the following code in console of google docs.

const input = document.querySelector(".docs-texteventtarget-iframe").contentDocument.activeElement;
    
// Insert the character in the document and trigger the save API call
const eventObj = document.createEvent("Event");
eventObj.initEvent("keypress", true, true);
eventObj.keyCode = 105;
input.dispatchEvent(eventObj);

You will see the character "i" inserting on the document.

Nellie answered 26/8, 2020 at 10:0 Comment(2)
Does this still work after Google Docs' update to canvas based rendering instead HTML based rendering?Benumb
It doesn't appear to work.Coma
C
6

Seems like Google Docs have special iframe to handle keyboard events. Here is it’s contents:

<html>
    <head></head>
    <body spellcheck="false" role="textbox" aria-label="Document content" contenteditable="true" style="background-color: transparent;"></body>
</html>

Just dispatch keyboard events to this document to print characters on google doc.

Copyboy answered 9/12, 2014 at 21:6 Comment(3)
is there an equivalent to this for google spreadsheets?Schaab
Does this still work after Google Docs' update to canvas based rendering instead of HTML based rendering?Benumb
Doesn't appear to.Coma

© 2022 - 2024 — McMap. All rights reserved.