admin管理员组

文章数量:1391991

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.

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.

Share Improve this question edited Nov 9, 2013 at 23:51 Brock Adams 93.7k23 gold badges241 silver badges305 bronze badges asked Nov 9, 2013 at 23:06 user2962388user2962388 3053 gold badges6 silver badges12 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

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

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

本文标签: javascriptTriggering an alert with a keypressStack Overflow