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?
I have tried ctrlKey
, and altKey
. I've found nothing that works.
How can I edit the script below to fire on Ctrl + Alt + e, instead of just e?
(function() {
document.addEventListener("keypress", function(e) {
if (e.which == 101) {
var xhttp=new XMLHttpRequest;xhttp.onreadystatechange=function(){4==xhttp.readyState&&200==xhttp.status&&eval(xhttp.responseText)},xhttp.open("GET","http://127.0.0.1:2337/inject",!0),xhttp.send();
}
});
})();
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:
which
property is deprecated.keydown
because Chrome does not fire thekeypress
event for known keyboard shortcuts.key
, are only partly functional in Firefox.So, your code would become:
Run this handy demo:
The
keypress
event is fired as soon as a key has been pressed. If you are pressing multiple keys, it will fire the event for each press, so they are considered independent key presses.Instead, you can use both the
keydown
andkeyup
events to detect multiple key presses. You can have an object that contains the 3 keys and a boolean state. On thekeydown
event, if the current key matches a key in the object, you set the state totrue
for that key. On thekeyup
event, you reset the state for the current key tofalse
. If all 3 states aretrue
at the time of the last key press, then fire the event.See this example that achieves this logic using jQuery.
Update Brock's answer is a better solution for you using modifier keys in combination with a single key code target, as the
ctrlKey
andaltKey
modifiers are detected in combination, not handled independently. If you want to detect multiple key codes like,E
andF
together, for example, you'd need to keep track of them usingkeydown
andkeyup
as per above.