cvan / keyboardevent-key-polyfill

polyfill for `KeyboardEvent.prototype.key`
https://cvan.io/keyboardevent-key-polyfill/
Creative Commons Zero v1.0 Universal
47 stars 15 forks source link

strange safari behavior #17

Open zys5945 opened 7 years ago

zys5945 commented 7 years ago

Idk if this is just a problem for me, but in my VM running mac 10.12.3, safari 10.0.3, I found that just by polyfilling KeyboardEvent.prototype will not affect KeyboardEvents fired by the browser. I had to manually catch the event then directly polyfilling its proto for it to work:

Polyfill function: ` function polyfill (target) { if(target != null){ if('key' in target) return false; }else{ if (!('KeyboardEvent' in window) || 'key' in KeyboardEvent.prototype) { return false; } } // Polyfill "key" on "KeyboardEvent" var proto = { get: function (x) { var key = keyboardeventKeyPolyfill.keys[this.which || this.keyCode];

    if (Array.isArray(key)) {
      key = key[+this.shiftKey];
    }

    return key;
  }
};
if(target != null)
  Object.defineProperty(target, 'key', proto);
else
  Object.defineProperty(KeyboardEvent.prototype, 'key', proto);
return proto;

} `

catching the event and handle it: this.editArea.addEventListener("keydown", e => { if(e.key == null) keyboardeventKeyPolyfill.polyfill(e.__proto__); }

Sorry for this uggly looking styling

zys5945 commented 7 years ago

Also, just realized, this will not work for keypress events as they have different key codes compared with keydown.

Take a press on "a" for example, e.which on keydown will give you 65, but e.which on keypress will give you 97