Simulating keyboard typing with JavaScript

Željko Šević - Aug 21 - - Dev Community

Simulating keyboard typing in JavaScript can be useful for automating tasks or testing applications. The KeyboardEvent API allows developers to trigger keyboard events programmatically.

Examples

  • The snippet below simulates pressing the Ctrl + Enter command. The bubbles flag ensures the event moves up through the DOM, so any elements higher up in the document can also detect and respond to it.
const event = new KeyboardEvent('keydown', {
  key: 'Enter',
  ctrlKey: true,
  bubbles: true,
});

document.dispatchEvent(event);
Enter fullscreen mode Exit fullscreen mode
  • The snippet below simulates pressing the Shift + Enter command on a specific input field.
const event = new KeyboardEvent('keydown', {
  key: 'Enter',
  shiftKey: true,
  bubbles: true,
});

document.querySelector('input').dispatchEvent(event);
Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player