keyCode and which are deprecated – so why is that not working?

Tags: , , ,



According to MDN Web Docs KeyboardEvent and Google Updates KeyboardEvent key and code are implemented while keyCode and which are deprecated.

With that in mind I should be able to dispatch keydown event as below:

document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: 'K',
        code: 'KeyK',
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
    })
);

Unfortunately it doesn’t work whilst if I add keyCode additionally this script works perfectly. Object with keyCode:

document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: 'K',
        code: 'KeyK',
        keyCode: 75,
        shiftKey: false,
        ctrlKey: false,
        metaKey: false
    })
);

Am I missing something? keyCode and which are deprecated so it should be possible to create working event without these elements. I cannot find anywhere answer for that.

I am using current version of Google Chrome (87). I test this script by sending k key to YouTube for play/pause video.

Answer

The “deprecated” status in the documentation is telling you that you shouldn’t rely on those attributes being present in events which you receive, because the browser developers are planning to stop including them in events which they create.

However, in this case, you are simulating the part of the code that the browser would normally perform, in creating the event. Neither you nor the browser has any way to know what the code receiving that event is going to look for.

If you leave out the deprecated attributes, you are emulating a future browser, and the YouTube site you’re testing on might not currently be ready to work with that future browser. You are better off setting all the attributes a current browser would set for that event.

Note that the developers of YouTube, while ultimately employed by the same company as the developers of Chrome, likely have very little connection. They will be updating their code to follow current best practices on a regular basis like any well-run development team, but that takes time, and has to be prioritised amongst everything else they’re working on.



Source: stackoverflow