I'm trying to simulate pressing the Enter key on an input field with Javascript so that the input field would get submitted as if the user pressed Enter on the keyboard. I'm using the newest version of Chrome (version 87.0.4280.88).
For example, I can submit the search field in Youtube by entering this code in the console:
document.querySelector("input#search").dispatchEvent(new KeyboardEvent("keydown", {keyCode: 13}))
It works, but uses the deprecated property "keyCode". If I replace keyCode: 13
with key: "Enter"
, the code just returns True without submitting the search. Why is this, given that the key property is recommended to be used instead of the keyCode one?
There are many posts on stackoverflow addressing this subject, but the offered code snippets that are supposed to simulate Enter key press just don't seem to work in many websites in my experience. What could be the reason behind this?