Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greasemonkey Javascript Key Press

I'm currently trying to make a GreaseMonkey script that will allow a user to press left or right on their keyboard and have that go to a previous comic strip or go to the next strip. I currently have some code up but it's not giving me any results.

function KeyCheck()
{
var KeyID = event.keyCode;
alert(KeyID);
}

document.onKeyDown = KeyCheck();

The code is just for debugging to see if it's actually executing but when I press a key nothing will happen on the page. I'm testing in Firefox also.

like image 907
NessDan Avatar asked Jan 24 '10 23:01

NessDan


2 Answers

So after Googling for a good 30 minutes, I found out GreaseMonkey doesn't support onkeydown out of the box. I had to use a function called "addEventListener". My final code returns the keyCode of a key pressed on the site properly:

function KeyCheck(e)
{
alert(e.keyCode);
}

window.addEventListener('keydown', KeyCheck, true);
like image 91
NessDan Avatar answered Oct 06 '22 00:10

NessDan


You shouldn't have the () after KeyCheck. Your current code runs KeyCheck and then attempts to set document.onKeyDown to the value returned. If you do it without the () it should instead set the function called KeyCheck to be run on the event.

Also, I think onKeyDown should be all lower case - it's document.onkeydown.

Further example, with an inline function:

document.onkeydown = function() { alert("key down") }

works whereas

document.onkeydown = alert("key down");

doesn't.

like image 23
Tim Perry Avatar answered Oct 06 '22 02:10

Tim Perry