2

I am trying to write a userscript that types something in input tag with class name="chat-input" and presses enter.The userscript as of now only types "Hello!" in chat-input but does not simulate enter key. Any idea why?

var msg = "Hello!";

        var target = document.getElementsByClassName("chat-input")[0];
                             target.value = msg ;
        var eventType = "textInput";
        var evt = document.createEvent("TextEvent");
        evt.initKeyEvent("keypress", true, false, window, 0, 0, 0, 0, 13, 13);

        target.focus();
        target.dispatchEvent(evt);

The input box does not have any submit button only way to send message is by enter key

Nabil Mehtab
  • 37
  • 1
  • 3
  • 7

1 Answers1

3

Copying the answer with modification from here.

const ke = new KeyboardEvent("keydown", {
    bubbles: true, cancelable: true, keyCode: 13
});
target.dispatchEvent(ke);

According to that post, initKeyEvent is only for Firefox.

Christopher Janzon
  • 1,039
  • 11
  • 22