Search code examples
javascriptgoogle-chromepolyfills

JavaScript make basic polyfill for event.key alert event.keyCode to modernize Chrome


In short, how do I make alert(event.key) return the event.keyCode?

I just need to know how to make it so alert(event.key); becomes alert(event.keyCode); because once I'm that far I can remap everything just fine.

The event.keyCode method has been deprecated. I've never messed with JavaScript prototype and it is my understanding that it's used to essentially create a polyfill for older browsers (like say, Chrome 40 that doesn't support event.key because ...?). I'm not looking for the entire function to be coded out, I just want to alert the keyCode because from there I can figure out the mapping code and update this question with the working code.

What I've been experimenting with:

window.onkeydown = function(event)
{
 if (!event.key)
 {
  Object.defineProperty(String.prototype,'key',
  {
   enumerable: false,
   configurable: false,
   writable: false,
   value: function(event.keyCode)
   {
    alert('event.keyCode = '+event.keyCode);
   }
  });
 }

 alert('event.key = '+event.key);
}

No frameworks.


Solution

  • Combining dandavis and my comments, here is a shim with a little error handling

    (function () {
        var ev;
        try {
            ev = new KeyboardEvent('keydown');
            if (!('key' in ev)) {
                if (!('keyCode' in ev))
                    if (console && console.warn)
                        console.warn('Someting went wrong setting up keyboardEvent.key; no keyboardEvent.keyCode');
                Object.defineProperty(
                    KeyboardEvent.prototype,
                    'key',
                    {get: function () {return this.keyCode;}}
                );
            }
        } catch (e) {
            if (console && console.warn)
                console.warn('Someting went wrong setting up keyboardEvent.key; an error was thrown');
        }
    }());