Monday, May 13, 2024
3
rated 0 times [  6] [ 3]  / answers: 1 / hits: 43949  / 15 Years ago, sun, december 13, 2009, 12:00:00

I'm trying to fire a keyboard event to a page using javascript on Chrome.
I had an approach that used to work on Firefox:



pressKey = function(key, shift) {
var evt = document.createEvent('KeyboardEvent');
evt.initKeyEvent(keypress, false, true, null, false, false,
shift, false, keyCode(key), key.charCodeAt(0));
document.dispatchEvent(evt);
}


where key is the desired key and keyCode changes lowercase letters into highercase and also calls charCodeAt().



My problem is that events on Safari/Chrome don't have initKeyEvent, but initKeyboardEvent. The main difference I could notice was that you have to pass the key as a keyIdentifier (which looks like a unicode character) instead of passing the keycode and the keychar. Nonetheless I still can't manage to make it work.



I've also tried the JQuery approach described here without success.



EDIT:
I debugged this a little further and it seems that the event on Chrome does trigger the listeners, but keyCode/charCode is always 0. I've tried to set evt.keyCode or evt.charCode with no success either.


More From » google-chrome

 Answers
54

I just want to throw this basic snippet out there. It works in Chrome and is based on the hack mentioned by Paul Irish.

It uses charCode instead of keyCode (which can be useful in certain situation), but adapt to keyCode if you so please.



var keyboardEvent = new KeyboardEvent('keypress', {bubbles:true}); 
Object.defineProperty(keyboardEvent, 'charCode', {get:function(){return this.charCodeVal;}});
keyboardEvent.charCodeVal = [your char code];
document.body.dispatchEvent(keyboardEvent);

[#98079] Wednesday, December 9, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaitlyn

Total Points: 421
Total Questions: 73
Total Answers: 100

Location: South Georgia
Member since Sat, Jul 25, 2020
4 Years ago
kaitlyn questions
Mon, Jan 10, 22, 00:00, 2 Years ago
Wed, Jun 2, 21, 00:00, 3 Years ago
Wed, Jan 20, 21, 00:00, 3 Years ago
Mon, Dec 2, 19, 00:00, 5 Years ago
;