V
V
Valery Chupurnov2017-02-28 11:49:34
JavaScript
Valery Chupurnov, 2017-02-28 11:49:34

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)

But I understand that this just emulates the event so that the addEventListener fires, but the event itself does not actually occur. And this code does not work, in the textarea that I give it, the new line does not appear.
UPD
If anyone is interested, then this code works in 3 major browsers, as well as in phantomjs
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

1 answer(s)
M
M-ka, 2017-02-28
@M-ka

"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 question

Ask a Question

731 491 924 answers to any question