Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create KeyboardEvent with specific keyCode

I'm trying to simulate a keydown event in a unit test (angular2/TypeScript). I do not always have a DebugElement available, so I'm trying to emit the event on a native element. The problem I have is how to define the keyCode when creating the KeyboardEvent. The keyCode is not defined as part of KeyboardEventInit definition, and on the KeyboardEvent itself it is only exposed as a readonly property.

Simply just adding a keyCode property (and set the obj type as ) doesn't work either.

    let elm = <HTMLElement>content.nativeElement;
    let ev = new KeyboardEvent('keydown', {
        code: '123',
        //keyCode: 345,
        key: 'a',
    });
    elm.dispatchEvent(ev);

Any suggestions ?

Edit: According to the mdn link, keyCode is deprecated and should not be used, instead 'code' should be used. https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

like image 803
Jesper Kristiansen Avatar asked Nov 10 '16 17:11

Jesper Kristiansen


People also ask

What is e keycode === 13?

key 13 keycode is for ENTER key.

How do you use KeyboardEvent codes?

Pressing the physical Q key on that keyboard will result in a KeyboardEvent with a code attribute set to "KeyQ" . This is true regardless of keyboard layout, and regardless of any other modifier keys.


2 Answers

I still think that this is a bug from the Typescript's side because of the initializer LanguageEvent has. In any case, a workaround would be to use Object.define to set the keyCode.

let arrowRight = new KeyboardEvent('keydown');
Object.defineProperty(arrowRight, 'keyCode', {
    get : () => 39
});
console.log(arrowRight.keyCode, arrowRight.key, arrowRight.code);

No matter the fact that the keyCode is deprecated, that doesn't mean that the initializer shouldn't support it. The most strong argument is the fact that Internet Explorer 9 and 11 depends on that and they don't support the code https://caniuse.com/#search=event.code or fully support the key https://caniuse.com/#search=event.key So I think that LanguageEvent should allow keyCode in its initializer.

let arrowRight = new KeyboardEvent('keydown', { keyCode: 39 });
like image 143
Rambou Avatar answered Sep 23 '22 18:09

Rambou


keyCode is deprecated, Angular itself operates with key — I suggest you rewrite your logic to use it too. Keep in mind that it is browser dependent — in IE space bar is Space and in other browsers it is . Also Esc and Escape are different. Don't remember any other ones that differ.

like image 35
waterplea Avatar answered Sep 20 '22 18:09

waterplea