I am trying to make a script run when Ctrl + Alt + e is pressed.
How can Tampermonkey fire on a simultaneous ctrl, alt, and e key?
Refer to the W3C spec for keyboard events. Several boolean attributes are provided to determine if modifier keys were pressed in conjunction with whatever target key you are interested in. They are:
ctrlKey -- The "Control" key was also pressed.shiftKey -- The "Shift" key was also pressed.altKey -- The "Alt" key was also pressed.metaKey -- The "Meta" key was also pressed.Other important notes:
keydown because Chrome does not fire the keypress event for known keyboard shortcuts.key, are only partly functional in Firefox.So, your code would become:
document.addEventListener ("keydown", function (zEvent) {
if (zEvent.ctrlKey && zEvent.altKey && zEvent.key === "e") { // case sensitive
// DO YOUR STUFF HERE
}
} );
Run this handy demo (updated now that key has full support):
var targArea = document.getElementById ("keyPrssInp");
targArea.addEventListener ('keydown', reportKeyEvent);
function reportKeyEvent (zEvent) {
var keyStr = ["Control", "Shift", "Alt", "Meta"].includes(zEvent.key) ? "" : zEvent.key + " ";
var reportStr =
"The " +
( zEvent.ctrlKey ? "Control " : "" ) +
( zEvent.shiftKey ? "Shift " : "" ) +
( zEvent.altKey ? "Alt " : "" ) +
( zEvent.metaKey ? "Meta " : "" ) +
keyStr + "key was pressed."
;
$("#statusReport").text (reportStr);
//--- Was a Ctrl-Alt-E combo pressed?
if (zEvent.ctrlKey && zEvent.altKey && zEvent.key === "e") { // case sensitive
this.hitCnt = ( this.hitCnt || 0 ) + 1;
$("#statusReport").after (
'Bingo! cnt: ' + this.hitCnt + '
'
);
}
zEvent.stopPropagation ();
zEvent.preventDefault ()
}