Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically send keys to input using dispatchEvent

I'm trying to send characters to an input element based on user actions.

I'm trying to use KeyboardEvent with dispatchEvent but whatever I do, it doesn't work

For example:

let keyEvent = new KeyboardEvent();
keyEvent.key = 'a';
keyEvent.keyCode = 'a'.charCodeAt(0);
keyEvent.which = event['keyCode'];
keyEvent.altKey = false;
keyEvent.ctrlKey = true;
keyEvent.shiftKey = false;
keyEvent.metaKey = false;
keyEvent.bubbles = true;

Not sure if this is correct, but I have dispatched it as follows:

  document.querySelector('input').dispatchEvent(keyEvent);
  document.activeElement.dispatchEvent(keyEvent);
  document.dispatchEvent(keyEvent);

DEMO

If I first focus the input before clicking the button nothing really happens. Any suggestions what might go wrong here ?

like image 556
Jeanluca Scaljeri Avatar asked Jun 01 '26 20:06

Jeanluca Scaljeri


2 Answers

Actually, due to security reasons, dispatching a KeyboardEvent to an input element does not generate the action you expect.

The KeyboardEvent document makes it quite clear:

Note: manually firing an event does not generate the default action associated with that event. For example, manually firing a key event does not cause that letter to appear in a focused text input. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

So the dispatchEvent stuff simply won't work.

Alternatively, consider manipulating the input element directly.

like image 92
Microloft Avatar answered Jun 03 '26 10:06

Microloft


In base of your code here is a eventKeyboard, but: - after dispatch keyevent, wath's next?, who is listener? - ... i cant underdstand at all

document.querySelector('button').addEventListener('mousedown', (e) => {
        e.preventDefault();
      e.stopImmediatePropagation();
        e.stopPropagation();

      console.log('send key');

    /*let keyEvent = new KeyboardEvent();

    keyEvent.key = 'a';
    keyEvent.keyCode = 'a'.charCodeAt(0);
    keyEvent.which = event['keyCode'];
    keyEvent.altKey = false;
    keyEvent.ctrlKey = true;
    keyEvent.shiftKey = false;
    keyEvent.metaKey = false;
    keyEvent.bubbles = true;
    console.log(keyEvent);       */
    var keyEvent = new KeyboardEvent("keydown", {
      bubbles : true,
      cancelable : true,
      char : "A",
      key : "1",
      shiftKey : true,
      keyCode : 81
  });
      document.querySelector('input').dispatchEvent(keyEvent);
      document.activeElement.dispatchEvent(keyEvent);
      document.dispatchEvent(keyEvent);
    console.log(keyEvent);
});
like image 20
Álvaro Touzón Avatar answered Jun 03 '26 08:06

Álvaro Touzón



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!