Google Docs 模拟键盘

Ser*_*nov 5 javascript keypress google-docs

我需要使用 JavaScript 在 google docs 中模拟键盘,以便能够在光标位置打印或擦除字符。
不幸的是,模拟按键事件的解决方案对我不起作用。我尝试使用和不使用 jQuery。
经过一番调查,我发现 Google Docs 有虚拟键盘。单击虚拟键调用此函数:

C.MOa = function(a) {
  this.dispatchEvent(new Q(Td, {keyCode: a}))
};
Run Code Online (Sandbox Code Playgroud)

哪里Td是字符串“动作”和Q一些事件类。
用java脚本发送这个事件的正确方法是什么?还有其他方法可以在 Google Docs 中模拟键盘吗?

Yar*_*lav 6

似乎 Google Docs 有特殊的 iframe 来处理键盘事件。这是\xe2\x80\x99s 的内容:

\n\n
<html>\n    <head></head>\n    <body spellcheck="false" role="textbox" aria-label="Document content" contenteditable="true" style="background-color: transparent;"></body>\n</html>\n
Run Code Online (Sandbox Code Playgroud)\n\n

只需将键盘事件分派到此文档即可在 google doc 上打印字符。

\n


小智 6

将以下代码粘贴到 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);
Run Code Online (Sandbox Code Playgroud)

您将看到在文档中插入了字符“i”。