Frage

I am writing a Greasemonkey script. I want to trigger a certain code to run when the user presses the "Q" key. I did a little bit of research, and most of the sources I saw suggested using window.onkeypress.

To test this method, I created a userscript set to run when the users presses Q. Here is my code:

window.onkeypress = function(event) {
   if (event.keyCode == 81) {
   alert("This is a test.")
   }
}


However, upon pressing the Q key, nothing happened. I am wondering if anyone knows why this may be and what I can do to correct it.

In addition, if anyone knows of any other methods I can use to achieve the same effect, it would be greatly appreciated.

War es hilfreich?

Lösung

keypress events don’t receive a keyCode; try handling keydown instead.

window.onkeydown = function(event) {
   if (event.keyCode === 81) {
      alert("This is a test.");
   }
};
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top