How to simulate multiple keypress in JavaScript

Let's assume that you want to simulate multiple key events such as CTRL + V.

First, create a listener that displays a message on keydown:

javascript
window.addEventListener('keydown', (e) => {

    if(e.ctrlKey && e.key === 'v'){
        console.log('CTRL + V');
    }
    
});

Now you can dispatch the event:

javascript
document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: "v",
        ctrlKey: true,
        bubbles: true,
        metaKey: true   
    })
);

As you can see, you can configure a secondary key on the KeyboardEvent object. However, you can use only predefined keys (ctrlKey and metaKey).

But what happens if you don't use conventional key combinations? For example, let's say that you want to catch A + V.

Non-standard keyboard combinations

In this case, you'll need to create 2 listeners (keydown and keyup):

javascript
var keys = {};

window.addEventListener('keydown', (e) => {
    
    keys[e.key] = true;
    
    if(keys['a'] && keys['v']) 
        console.log('A + V');
    
});

window.addEventListener('keyup', (e) => {

    keys[e.key] = false;
    
});

Now you can dispatch the events:

javascript
document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: "v",
        bubbles: true
    })
);

document.dispatchEvent(
    new KeyboardEvent("keydown", {
        key: "a",
        bubbles: true
    })
);

Remember that you can simulate the release of the keys after dispatching the event as well:

javascript
document.dispatchEvent(
    new KeyboardEvent("keyup", {
        key: "v",
        bubbles: true
    })
);

document.dispatchEvent(
    new KeyboardEvent("keyup", {
        key: "a",
        bubbles: true
    })
);

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.