Reputation: 6195
I would like to have keyboard shortcuts to change the color of a selected text in google docs.
I am able to get the button elements by id but when I send click()
to that element nothing happen (here is my try with the bold button used for debug because it's simpler than what I want to do with button textColorButton
)
var button = document.getElementById("boldButton");
alert(button.innerHTML); // working
button.click(); // not working
I also though about getting the selection and then apply a style but the getSelection is empty:
var text = document.getSelection();
alert(text); // empty
Here is my script so far:
// ==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
}
}
Upvotes: 2
Views: 1169
Reputation: 6195
The trick to click a button is to do this:
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
button.dispatchEvent(clickEvent);
Here is the full script:
// ==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);
}
Upvotes: 1