Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing a Keyboard Event in Safari, using JavaScript

I'm trying to simulate a keyboard event in Safari using JavaScript.

I have tried this:

var event = document.createEvent("KeyboardEvent"); event.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 115, 0); 

...and also this:

var event = document.createEvent("UIEvents"); event.initUIEvent("keypress", true, true, window, 1); event.keyCode = 115; 

After trying both approaches, however, I have the same problem: after the code has been executed, the keyCode/which properties of the event object are set to 0, not 115.

Does anyone know how to reliably create and dispatch a keyboard event in Safari? (I'd prefer to achieve it in plain JavaScript if possible.)

like image 376
Steve Harrison Avatar asked Jun 07 '09 08:06

Steve Harrison


People also ask

How do I use keyboard events in JavaScript?

There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.

How do I trigger an event on my keyboard?

keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc. keyup: This event is triggered when a key is released.

Which JavaScript event will fire when a key is pressed?

keydown – fires when you press a key on the keyboard and it fires repeatedly while you holding down the key.


1 Answers

I am working on DOM Keyboard Event Level 3 polyfill . In latest browsers or with this polyfill you can do something like this:

element.addEventListener("keydown", function(e){ console.log(e.key, e.char, e.keyCode) })  var e = new KeyboardEvent("keydown", {bubbles : true, cancelable : true, key : "Q", char : "Q", shiftKey : true}); element.dispatchEvent(e);  //If you need legacy property "keyCode" // Note: In some browsers you can't overwrite "keyCode" property. (At least in Safari) delete e.keyCode; Object.defineProperty(e, "keyCode", {"value" : 666}) 

UPDATE:

Now my polyfill supports legacy properties "keyCode", "charCode" and "which"

var e = new KeyboardEvent("keydown", {     bubbles : true,     cancelable : true,     char : "Q",     key : "q",     shiftKey : true,     keyCode : 81 }); 

Examples here

Additionally here is cross-browser initKeyboardEvent separately from my polyfill: (gist)

Polyfill demo

like image 51
termi Avatar answered Sep 28 '22 15:09

termi