Tuesday, April 2, 2019

How to handle KeyboardEvent in different browsers

    



How to handle KeyboardEvent in different browsers (IE, Chrome, Safari and Firefox)


KeyboardEvent.keyCode - This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.

The value of keypress event is different between browsers. IE and Google Chrome set the KeyboardEvent.charCode value. Gecko sets 0 if the pressed key is a printable key, otherwise it sets the same keyCode as a keydown or keyup event.

Google Chrome and Safari have implemented KeyboardEvent.keyIdentifier, which was defined in a draft specification but not the final spec.


Google Chrome, Chromium and Safari must decide the value from the input character. If the inputting character can be inputted with the US keyboard layout, they use the keyCode value on the US keyboard layout.

This example works in Angular 6 and Typescript 2.9.2

/**

     * Allow key codes for special events
     * Del - IE Key in Numeric keypad
     * Decimal - IE Key in Numeric keypad
     * Subtract - IE Key in Numeric keypad
     * Left, Right - IE Keys
     */

specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'Delete', 'Del', '-', 'Decimal', 'ArrowLeft', 'ArrowRight', 'Left', 'Right', 'Subtract'];

//event.key is not working with Safari 5.x so we had to go with keyCode

specialKeyCodes: Array<any> = [9, 35, 36, 37, 39, 46, 48, 48, 50, 51, 52, 53, 54, 55, 56, 57, 190];

@HostListener('keydown', ['$event'])

  onKeyDown(event: KeyboardEvent) {
   

    if ((specialKeys.indexOf(event.key) !== -1) || (specialKeyCodes.indexOf(event.keyCode) !== -1)) {

      // some action......
    }
    //......

}