Answer the question
In order to leave comments, you need to log in
How to simulate a user keypress in JavaScript?
Good time. I write tests for the text editor on mocha.
The task is to simulate pressing the Enter key on the div [contenteditable] tag.
In this case, you need to see what will happen in this div after this pressing.
Question: is it allowed in the browser programmatically through events to press a key in the input field so that the field reacts and adds the desired character.
On the Internet they write:
var keyboardEventdown= new KeyboardEvent('keydown', {bubbles:true, key: 'Enter', code: 'Enter', which: 13});
Object.defineProperty(keyboardEventdown, 'charCode', {value: 0});
Object.defineProperty(keyboardEventdown, 'which', {value: 13});
Object.defineProperty(keyboardEventdown, 'keyCode', {value: 13});
editor.dispatchEvent(keyboardEventdown)
var simulateKeyPress = function (type, keyCodeArg, element) {
var evt = document.createEvent('HTMLEvents')
evt.initEvent(type, true, false);
evt.keyCode = keyCodeArg;
evt.which = keyCodeArg;
element.dispatchEvent(evt);
}
simulateKeyPress('keydown', 13, editor.editor);
Answer the question
In order to leave comments, you need to log in
"Question: is it allowed in the browser programmatically through events to press a key in the input field so that the field reacts and adds the desired character."
Answer: yes, it is allowed, but with reservations and not in this wording of the question. In some browsers, even the api provides for something similar to conduct autotests .... But it all comes down to rewriting the content and then calling the desired event or firing the event on the element and passing information to it in the desired structure (well, everyone rewrites the event handler to suit their needs ....)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question