简体   繁体   中英

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM