gpt4 book ai didi

javascript - 谷歌文档 : click a button or change style with userscript (tampermonkey)

转载 作者:行者123 更新时间:2023-11-30 20:35:49 25 4
gpt4 key购买 nike

我想要使用键盘快捷键来更改 google 文档中选定文本的颜色。

我能够通过 id 获取按钮元素,但是当我向该元素发送 click() 时,什么也没有发生(这是我尝试使用用于调试的粗体按钮,因为它比我的更简单想用按钮 textColorButton )

var button = document.getElementById("boldButton");
alert(button.innerHTML); // working
button.click(); // not working

我也想获取选择然后应用样式,但 getSelection 是空的:

var text = document.getSelection();
alert(text); // empty

到目前为止,这是我的脚本:

// ==UserScript==
// @name Google docs
// @match https://docs.google.com/document/d/#######
// @require http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// @require http://cdnjs.cloudflare.com/ajax/libs/sugar/1.3/sugar.min.js
// ==/UserScript==

var editingIFrame = $('iframe.docs-texteventtarget-iframe')[0];
if (editingIFrame) {
editingIFrame.contentDocument.addEventListener("keydown", hook, false);
}
function hook(key) {
if (key.ctrlKey && key.altKey && key.code === "KeyE") {
var button = document.getElementById("boldButton");
button.click(); // not working
}
}

最佳答案

点击按钮的技巧是这样做的:

var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
button.dispatchEvent(clickEvent);

这是完整的脚本:

// ==UserScript==
// @name Google docs
// @match https://docs.google.com/document/d/#########
// @require http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
// ==/UserScript==
// sources:
// for iframe https://stackoverflow.com/a/46217408/3154274
// for switch https://stackoverflow.com/q/13362028/3154274
// combinaison of key https://stackoverflow.com/a/37559790/3154274
// dispatchEvent https://stackoverflow.com/a/33887557/3154274
var editingIFrame = $('iframe.docs-texteventtarget-iframe')[0];
if (editingIFrame) {
editingIFrame.contentDocument.addEventListener("keydown", hook, false);
}

function hook(key) {
if (key.ctrlKey && key.altKey && key.code === "KeyY") {
var button = document.getElementById("textColorButton");
var color = document.querySelector('[title="light red berry 3"]');
triggerMouseEvent(button, "mouseover");
triggerMouseEvent(button, "mousedown");
triggerMouseEvent(button, "mouseup");
triggerMouseEvent(color, "mouseover");
triggerMouseEvent(color, "mousedown");
triggerMouseEvent(color, "mouseup");
}

}

function triggerMouseEvent(node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
node.dispatchEvent(clickEvent);
}

关于javascript - 谷歌文档 : click a button or change style with userscript (tampermonkey),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com