Google Docs simulate keyboard

╄→尐↘猪︶ㄣ 提交于 2021-02-07 18:27:24

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/27291021/google-docs-simulate-keyboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!