Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

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

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.

question from:https://stackoverflow.com/questions/65670737/keycode-and-which-are-deprecated-so-why-is-that-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...