Google文档:点击按钮或使用userscript更改样式(tampermonkey)

时间:2018-04-16 12:39:21

标签: javascript google-docs userscripts tampermonkey

我想使用键盘快捷键来更改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
    }
}

1 个答案:

答案 0 :(得分:1)

单击按钮的技巧是:

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);
}