I'm trying to send characters to an input element based on user actions.
I'm trying to use
dispatchEvent but whatever I do, it doesn't work
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);
If I first focus the input before clicking the button nothing really happens. Any suggestions what might go wrong here ?
Actually, due to security reasons, dispatching a
KeyboardEvent to an
input element does not generate the action you expect.
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.
dispatchEvent stuff simply won't work.
Alternatively, consider manipulating the
input element directly.